<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 订单编辑类
 * @package  module/base/bill
 * @author   allen.qiang
 * @version 1.0
 */

class billEdit {

    private $dbca;

    public function __construct( &$dbca ) {
        $this->dbca = $dbca;
    }

    public function creareBillData( &$bill_array, $operator=null ) {

        //加载类文件
        quanli_include('module/base/customer/quanliCust.class.php');
        quanli_include('module/base/system/sysRegion.class.php');
        quanli_include('module/func/eai.func.php');
        //add by allen.qiang 20141022 系统中操作信息中“操作人”切换为中文 --start
        global $G_PGLOB;
        //add by allen.qiang 20141022 系统中操作信息中“操作人”切换为中文 --end
        //实例crm类
        $ebsigEai = eai_crm();

        //实例地址类
        $sysRegion = new sysRegion( $this->dbca );

        //实例会员类
        $quanliCust = new quanliCust();

        //订单操作记录数组
        $bill_log_array = array(
            'goods' => array(),
            'other' => array(),
            'operator' => ''
        );

        //临时数组
        $temp_array = array(
            'goods_store' => array(), //用于检查库存
            'bill_promotion' => array(), //查询订单促销
            'pay_id' => array(),
            'pay_name' => array(),
            'goods' => array(),
            'coupon_code' => array(),
            'card_code' => array(),
            'paying_agent_str' => array()
        );

        $bill_array['master']['bill_money'] = 0;                                                 //订单金额
        $bill_array['master']['bill_totalMoney'] = 0;                                           //商品总金额
        $bill_array['master']['bill_totalPaid'] = 0;                                            //商品实售总金额
        $bill_array['master']['bill_receivable_money'] = 0;                                    //订单应收金额
        $bill_array['master']['bill_totalPoints'] = 0;                                          //商品总赠送积分
        $bill_array['master']['bill_subtract_money'] = 0;                                       //订单立减金额
        $bill_array['master']['bill_coupon_money'] = 0 ;                                        //订单优惠券抵扣金额
        $bill_array['master']['bill_points_money'] = 0;                                          //积分抵扣金额
        $bill_array['master']['bill_balance_money'] = 0;                                        //余额抵扣金额
        $bill_array['master']['bill_card_money'] = 0;                                            //订单代金卡抵扣金额
        $bill_array['master']['bill_totalAmount'] = 0;                                           //商品总数量
        $bill_array['master']['total_weight'] = 0;                                                //商品总重量
        $bill_array['master']['bill_accessories_money'] = 0;                                    //配件总金额
        $bill_array['master']['bill_paying_agent_money'] = 0;                                   //代付订单金额
        $bill_array['master']['tableware_amount'] = 0;                                           //餐具数量
        $bill_array['master']['candle_amount'] = 0;                                               //蜡烛数量


        $datetime = date(G_DEFAULT_DATETIME_FORMAT); //下单时间

        try {

            //生成订单号 和 订单编号
            $bill_no = generate_seqno('seqno_bill', null, true);
            $arg_array = array(
                'id' => $bill_array['master']['cityid']
            );
            $city_array = $sysRegion->getAreaManageList($arg_array);
            if(!$city_array){
                throw new Exception('城市没有找到', 404);
            }
            $bill_code = $city_array[0]['alias'] . get_bill_code( 'seqno_bill_code' . $city_array[0]['alias'] );

            //查询会员信息
            $arg_array = array(
                'pcustID' => $bill_array['pcustID']
            );
            $customer_array = $quanliCust->searchCustomerDetail( $arg_array );
            if (!$customer_array) {
                throw new Exception('会员信息没有找到', 404);
            }
            $custID = $customer_array['custID'];
            if (empty($operator)) {
                $operator = $custID;
            }

            //商品促销、订单促销、会员折扣促销
            $bill_array['bill_promotion_array'] = array();

            $bill_goods_array = $bill_array['goods'];
            $bill_array['goods'] = array();

            //保存订单商品信息（普通商品）
            if (isset($bill_goods_array['general'])) {

                foreach ($bill_goods_array['general'] as &$goods_array) {

                    if(isset($goods_array['is_buy']) && $goods_array['is_buy'] == 0)
                        continue;

                    //手动调价
                    if(isset($goods_array['adjustPrice']) && $goods_array['adjustPrice'] > -1 && $goods_array['adjustPrice'] != ''){
                        $goods_array['price'] = $goods_array['adjustPrice'];
                    }

                    //统计商品信息
                    $bill_array['master']['bill_totalMoney'] += $goods_array['salePrice'] * $goods_array['goods_amount'];    //商品总金额
                    $bill_array['master']['bill_totalPaid'] += $goods_array['price'] * $goods_array['goods_amount'];         //商品实售总金额
                    $bill_array['master']['bill_totalAmount'] += $goods_array['goods_amount'];                               //商品总数量
                    $temp_array['goods'][] = $goods_array['goodsName'];

                    $bill_goods_no = generate_seqno('seqno_bill_goods', null, true); //商品流水号

                    $goods_array['accessories_money'] = 0; //商品额外购买的配件金额
                    $goods_array['tableware_amount'] = 0;
                    $goods_array['extra_tableware_amount'] = 0;
                    $goods_array['candle_amount'] = 0;
                    $goods_array['extra_candle_amount'] = 0;

                    if ($goods_array['fittings']) {

                        foreach($goods_array['fittings'] as &$fittings) {

                            if ($fittings['forsale'] == 1 && empty($fittings['buyNum'])) {
                                continue;
                            }

                            if ($fittings['fitID'] == 51){
                                $goods_array['tableware_amount'] += $fittings['quantity'];
                                $bill_array['master']['tableware_amount'] += $fittings['quantity'];
                            } elseif ($fittings['fitID'] == 52) {
                                $goods_array['extra_tableware_amount'] += $fittings['buyNum'];
                                $bill_array['master']['tableware_amount'] += $fittings['buyNum'];
                            } elseif ($fittings['fitID'] == 53) {
                                $goods_array['candle_amount'] += $fittings['quantity'];
                                $bill_array['master']['candle_amount'] += $fittings['quantity'];
                            } elseif ($fittings['fitID'] == 55) {
                                $goods_array['extra_candle_amount'] += $fittings['buyNum'];
                                $bill_array['master']['candle_amount'] += $fittings['buyNum'];
                            }

                            $bill_array['fittings'][]= array(
                                'timeStamp' => $datetime,
                                'creator'  => $operator,
                                'createTime'  => $datetime,
                                'bill_goods_no'=> $bill_goods_no,
                                'fitID'  => $fittings['fitID'],
                                'fitName'  => $fittings['fitName'],
                                'fitUnit'  => $fittings['fitUnit'],
                                'quantity'  => $fittings['quantity'],
                                'buyNum'  => $fittings['buyNum'],
                            	//add by yim.hu FUN-BK-0009  单价 start
                            	//'buyMoney'  => $fittings['price']
                                'buyMoney'  => $fittings['buyMoney']
                            	//add by yim.hu FUN-BK-0009  单价 end
                            );

                            if ($fittings['forsale'] == 1) {
                                $bill_array['master']['bill_accessories_money'] += $fittings['buyMoney'] * $fittings['buyNum'];
                                $goods_array['accessories_money'] += $fittings['buyMoney'] * $fittings['buyNum'];
                            }
                        }
                    }

                    //保存订单普通商品
                    $bill_array['goods'][$bill_goods_no] = array(
                        'uuid'                     => make_uuid(),
                        'timeStamp'                => $datetime,
                        'creator'                  => $operator,
                        'createTime'               => $datetime,
                        'bill_no'                  => $bill_no,
                        'bill_goods_no'            => $bill_goods_no,
                        'goods_goodsID'           => $goods_array['goodsID'],
                        'goods_postID'            => $goods_array['postID'],
                        'goods_name'               => $goods_array['goodsName'],
                        'goods_spec'               => $goods_array['spec'],
                        'goods_amount'             => $goods_array['goods_amount'],
                        'goods_storePrice'        => $goods_array['salePrice'],
                        'goods_purchasePrice'     => $goods_array['price'],
                        'goods_points'             => $goods_array['salePoints'],
                        'goods_from'               => $goods_array['goods_from'],
                        'goods_groupID'            => 0,
                        'goods_status'             => 1,
                        'product_code'             => $goods_array['product_code'],
                        'birthday_card'            => $goods_array['birthday_card'],
                        'segmentation'             => $goods_array['segmentation'],
                        'goods_remark'             => $goods_array['productRemark'],     //商品生产备注
                        'tableware_amount'         => $goods_array['tableware_amount'],            //餐具数量
                        'extra_tableware_amount'   => $goods_array['extra_tableware_amount'],            //额外餐具数量（加购）
                        'candle_amount'            => $goods_array['candle_amount'],            //蜡烛数量
                        'extra_candle_amount'      => $goods_array['extra_candle_amount'],            //额外蜡烛数量（加购）
                        'auth_alter' => isset($goods_array['adjustPrice']) && $goods_array['adjustPrice'] != -1 ? 1 : 0
                    );

                    /*
                     *=====================================
                     * 保存商品促销记录
                     * @author create by allen.qiang
                     * ====================================
                     */
                    if(isset($goods_array['goods_promotion']) && !empty($goods_array['goods_promotion'])){

                        foreach($goods_array['goods_promotion'] as &$p){

                            $promotionID = $p['promotionID'];
                            $promotionName = $p['remark'];
                            switch($p['type']){
                                case 1: //商品立减
                                    $promotionInfo = '立减：'.$p['money'];
                                    break;
                                case 2:  //商品特价
                                    $promotionInfo = '特价：'.$p['money'];
                                    break;
                                case 6: //商品打折
                                    $promotionInfo = '折扣：'.$p['money'];
                                    break;
                            }

                            $bill_array['bill_promotion_array'][] = array(
                                'creator' => $operator,
                                'bill_no' => $bill_no,
                                'bill_goods_no' => $bill_goods_no,
                                'promotionID' => $promotionID,
                                'promotionName' => $promotionName,
                                'promotionInfo' => $promotionInfo,
                                'promotionType' => 2
                            );
                        }
                    }

                }

            }

            if ($bill_array['master']['bill_totalAmount'] == 0 && !isset($bill_array['bill_paying_agent'])) {
                throw new Exception('订单商品为空，请选择商品', 404);
            }

            /**
             * =========================
             * 商品新增日志
             * =========================
             */
            foreach($bill_array['goods'] as &$new_bill_goods) {
                $bill_log_array['goods'][] = '<span class="red">新增商品：</span>';
                $bill_log_array['goods'][] = '　　商品名称：' . $new_bill_goods['goods_name'];
                $bill_log_array['goods'][] = '　　商品规格：' . $new_bill_goods['goods_spec'];
                $bill_log_array['goods'][] = '　　商品价格：' . $new_bill_goods['goods_purchasePrice'];
                $bill_log_array['goods'][] = '　　　生日牌：' . $new_bill_goods['birthday_card'];
                $bill_log_array['goods'][] = '　　　　切分：' . $new_bill_goods['segmentation'];
                $bill_log_array['goods'][] = '　　　　备注：' . $new_bill_goods['goods_remark'];
                $bill_log_array['goods'][] = '　　餐具数量：' . $new_bill_goods['tableware_amount'];
                $bill_log_array['goods'][] = '加购餐具数量：' . $new_bill_goods['extra_tableware_amount'];
                $bill_log_array['goods'][] = '　　蜡烛数量：' . $new_bill_goods['candle_amount'];
                $bill_log_array['goods'][] = '额外蜡烛数量：' . $new_bill_goods['extra_candle_amount'];
                //add allen.qiang 20141110 新增商品流水号 ---start
                $bill_log_array['goods'][] = '商品流水号：' . $new_bill_goods['bill_goods_no'];
                //add allen.qiang 20141110 新增商品流水号 ---end
            }
            /**
             * =========================
             * 商品新增日志
             * =========================
             */

            //优惠券处理
            if (isset($bill_array['use_coupon']) && !empty($bill_array['use_coupon'])) {
                foreach($bill_array['use_coupon'] as $code => &$coupon) {
                    $bill_log_array['other'][] = '<span class="red">新增优惠券：</span>';
                    $bill_log_array['other'][] = '　　优惠券编号：' . $coupon['code'];
                    $bill_log_array['other'][] = '　　优惠券名称：' . $coupon['couponName'];
                    $bill_log_array['other'][] = '　　优惠券金额：' . $coupon['amount'];
                    $bill_log_array['other'][] = '　　优惠券使用类型：' . $GLOBALS['coupon_use_type'][$coupon['useType']];
                    $coupon['creator'] = $operator;
                    $coupon['bill_no'] = $bill_no;
                    $bill_array['master']['bill_coupon_money'] += $coupon['amount'];
                }
            }

            //代金卡处理
            if (isset($bill_array['use_card']) && !empty($bill_array['use_card'])) {
                foreach($bill_array['use_card']['detail'] as &$card) {
                    $bill_log_array['other'][] = '<span class="red">新增现金卡：</span>';
                    $bill_log_array['other'][] = '　　现金卡名称：' . $card['card_name'];
                    $bill_log_array['other'][] = '　　现金卡卡号：' . $card['card_no'];
                    $bill_log_array['other'][] = '　　现金卡面值：' . $card['face_value'];
                    $bill_log_array['other'][] = '　　现金卡抵扣金额：' . $card['deducation'];
                    $card['creator'] = $operator;
                    $card['bill_no'] = $bill_no;
                    $card['bill_code'] = $bill_code;
                    $bill_array['master']['bill_card_money'] += $card['deducation'];
                }
            }


            //积分处理
            if (isset($bill_array['use_points']) && !empty($bill_array['use_points'])) {
                $bill_array['master']['bill_points_money'] += $bill_array['use_points']['bill_points_money'];
            }

            //余额处理
            if (isset($bill_array['use_balance']) && !empty($bill_array['use_balance'])) {
                $bill_array['master']['bill_balance_money'] += $bill_array['use_balance']['balance'];
            }

            //代付订单处理
            if (isset($bill_array['bill_paying_agent']) && !empty($bill_array['bill_paying_agent'])) {

                $bill_paying_agent_array = $bill_array['bill_paying_agent'];
                $bill_array['bill_paying_agent'] = array();

                foreach($bill_paying_agent_array as $item) {
                    $bill_array['bill_paying_agent'][] = array(
                        'creator' => $operator,
                        'timeStamp' => $datetime,
                        'createTime' => $datetime,
                        'main_bill_no' => $bill_no,
                        'bill_no' => $item['bill_no'],
                        'bill_code' => $item['bill_code'],
                        'deliver_name' => $item['deliver_name'],
                        'bill_receivable_money' => $item['bill_receivable_money']
                    );

                    //代付订单日志
                    $bill_log_array['other'][] = '<span class="red">新增代付订单：</span>';
                    $bill_log_array['other'][] = '　　订单编号：' . $item['bill_code'];
                    $bill_log_array['other'][] = '　　代付金额：' . $item['bill_receivable_money'];

                    $bill_array['master']['bill_paying_agent_money'] += $item['bill_receivable_money'];
                    $temp_array['paying_agent_str'][] = $item['bill_code'];
                }
            }

            //修改运费
            if( isset($bill_array['alter_freight']) && $bill_array['alter_freight'] != ''){
                $deliver_feePaid = $bill_array['master']['deliver_feePaid'];
                $alter_freight = $bill_array['alter_freight'];
                $bill_array['master']['deliver_feePaid'] = $alter_freight;

                //修改运费日志
                $bill_log_array['other'][] = '新增修改运费：'.$deliver_feePaid . ' => ' . $alter_freight;
            }

            //会员折扣促销
            if(isset($bill_array['cut_rebate_money']) && $bill_array['cut_rebate_money'] > 0){
                $bill_array['bill_promotion_array'][] = array(
                    'creator' => $operator,
                    'bill_no' => $bill_no,
                    'bill_goods_no' => 0,
                    'promotionID' => $customer_array['rankID'],           //会员等级ID
                    'promotionName' => $customer_array['rankName'],      //会员等级名称
                    'promotionInfo' => '立减：'.$bill_array['cut_rebate_money'],
                    'promotionType' => 3
                );
            }


            /**
             * ========================================
             * 查询订单促销活动
             * @author create by allen.qiang
             * =========================================
             */

            //error_log(print_r($bill_array,1));
            //add by sunqiang
            quanli_require('module/base/activity/activitySpike.class.php');
            $activitySpike = new activitySpike;
            if( isset($bill_array['master']['billPromotion']) && $activitySpike->billPromotion_lv5 == $bill_array['master']['billPromotion'])
            {
                $bill_array['bill_promotion'] = null;
            }
            //add by sunqiang end

            if (isset($bill_array['bill_promotion']) && !empty($bill_array['bill_promotion'])) {

                foreach($bill_array['bill_promotion'] as &$p) {

                    $promotionInfo = '';
                    switch( $p['type'] ){
                        case 1: //订单立减
                            $bill_array['master']['bill_subtract_money'] += $p['subtractMoney'];
                            $promotionInfo = '立减：'.$p['subtractMoney'];
                            break;
                        case 2: //免运费
                            $promotionInfo = '免运费：'.$bill_array['master']['deliver_feePaid'];
                            $bill_array['master']['deliver_feePaid'] = 0;
                            break;
                        case 3: //赠送优惠券
                            foreach($p['coupon'] as &$coupon) {
                                $bill_array['coupon'][] = array(
                                    'uuid' => make_uuid(),
                                    'timeStamp' => $datetime,
                                    'creator' => $operator,
                                    'createTime' => $datetime,
                                    'bill_no' => $bill_no,
                                    'couponID' => $coupon['couponID'],
                                    'couponName' => $coupon['couponName'],
                                    'couponNum' => $coupon['couponNum'],
                                    'bill_status' => $p['bill_status']
                                );
                            }
                            $promotionInfo = '赠券：'.$p['remark'];
                            break;
                        case 4: //订单打折
                            $bill_array['master']['bill_totalPaid'] = round($bill_array['master']['bill_totalPaid'] * $p['subtractMoney'], 2);
                            $bill_array['master']['bill_accessories_money'] = round($bill_array['master']['bill_accessories_money'] * $p['subtractMoney'], 2);
                            $promotionInfo = '折扣：'.$p['subtractMoney'];
                            break;
                    }
                    $bill_array['bill_promotion_array'][] = array(
                        'creator' => $operator,
                        'bill_no' => $bill_no,
                        'bill_goods_no' => 0,
                        'promotionID' => $p['promotionID'],
                        'promotionName' => $p['promotionName'],
                        'promotionInfo' => $promotionInfo,
                        'promotionType' => 1
                    );
                }
            }

            //====================================
            //订单金额 = 蛋糕 + 配件 + 运费 + 代付
            //===================================
            $bill_array['master']['bill_money'] = $bill_array['master']['bill_totalPaid']
                + $bill_array['master']['bill_accessories_money']
                + $bill_array['master']['bill_paying_agent_money'];


            //=========================================================
            //==============订单应收金额 ==============================
            //============= = 订单金额===============================
            //============= - 订单立减金额=============================
            //============= - 优惠劵抵扣金额===========================
            //============= - 代金卡抵扣金额===========================
            //============= - 积分抵扣金额）===========================
            //=========================================================
            $bill_array['master']['bill_receivable_money'] = $bill_array['master']['bill_money']
                - $bill_array['master']['bill_subtract_money']
                - $bill_array['master']['bill_coupon_money']
                - $bill_array['master']['bill_card_money']
                - $bill_array['master']['bill_points_money']
                - $bill_array['master']['bill_balance_money'];
            //==========================================================
            //===================订单应收金额===========================
            //==========================================================
            if ($bill_array['master']['bill_receivable_money'] < 0) {
                $bill_array['master']['bill_receivable_money'] = 0;
            }


            $bill_array['master']['bill_money'] += $bill_array['master']['deliver_feePaid'];
            $bill_array['master']['bill_receivable_money'] += $bill_array['master']['deliver_feePaid'];

            //去零取整
            if( intval($bill_array['master']['bill_receivable_money']) != $bill_array['master']['bill_receivable_money'] ){

                //抹去的小数金额
                $erase_money = $bill_array['master']['bill_receivable_money'] - intval($bill_array['master']['bill_receivable_money']);
                $bill_array['master']['bill_receivable_money'] = intval($bill_array['master']['bill_receivable_money']);

                //记录下抹去的小数金额
                $bill_array['erase_money'] = array(
                    'creator' => $operator,
                    'bill_no' => $bill_no,
                    'erase_money' => $erase_money,
                );

            }

            $bill_array['master']['bill_received_money'] = $bill_array['master']['bill_money'] - $bill_array['master']['bill_receivable_money'];


            //大客户试吃订单
            if(isset($bill_array['master']['foretaste']) && $bill_array['master']['foretaste'] == 1){
                $bill_array['master']['bill_receivable_money'] = 0;
                $bill_array['master']['bill_received_money'] = 0;
                //$bill_array['master']['deliver_feePaid'] = 0;
                $bill_array['master']['is_big_customer'] = 1;
            }else{
                $bill_array['master']['is_big_customer'] = 0;
            }

            //这里让4种招待赠送、生日会蛋糕、补偿订单、市场推广 和试吃一样 价格
            if($bill_array['master']['billType'] == 2 || $bill_array['master']['billType'] == 3 ||  $bill_array['master']['billType'] == 5 ||  $bill_array['master']['billType'] == 7){
            	$bill_array['master']['bill_receivable_money'] = 0;
            	$bill_array['master']['bill_received_money'] = 0; 
		$bill_array['master']['is_big_customer'] = 0;

            }

            //用户获取积分
            $bill_array['master']['bill_totalPoints'] = floor($bill_array['master']['bill_receivable_money']/4);

            //最终应付金额
            $surplus_money = $bill_array['master']['bill_receivable_money'];

            //已支付的金额
            $paid = 0;

            //扣除余额
            if (isset($bill_array['use_balance'])) {

                //检查账户余额
                $result_array = $ebsigEai->searchCustAccount($bill_array['pcustID'], G_CASH_ID);
                if ($result_array['code'] != 200 || $result_array['data']['useableAccount'] < $bill_array['use_balance']['balance'])
                    throw new Exception('账户余额不足', 404);


                //生成一条余额付款的付款记录
                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => G_CASH_ID,
                    'payTypeName' => '余额',
                    'type' => 4,
                    'pay_amount' => $bill_array['use_balance']['balance'],
                    'deduct_amount' => $bill_array['use_balance']['balance']
                );

                $temp_array['pay_id'][] = G_CASH_ID;
                $temp_array['pay_name'][] = '余额';

                //余额抵扣金额参数
                $bill_array['use_balance']['argus_array'] = array(
                    'operator' => $operator,
                    'pcustID' => $bill_array['pcustID'],
                    'subjectId' => G_CASH_ID,
                    'amount' => $bill_array['use_balance']['balance'],
                    'remark' => '订单 '.$bill_no.' 冻结,账户余额'
                );

            }

            //使用了积分抵扣金额
            if (isset($bill_array['use_points']) && $bill_array['use_points']['points'] > 0) {

                //检查账户积分
                $result_array = $ebsigEai->searchCustAccount($bill_array['pcustID'], G_POINTS_ID);
                if ($result_array['code'] != 200 || $result_array['data']['useableAccount'] < $bill_array['use_points']['points'])
                    throw new Exception('账户积分不足', 406);

                //生成积分支付
                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => G_POINTS_ID,
                    'payTypeName' => '积分',
                    'type' => 5,
                    'pay_amount' => $bill_array['use_points']['points'],
                    'deduct_amount' => $bill_array['use_points']['points']
                );

                $temp_array['pay_id'][] = G_POINTS_ID;
                $temp_array['pay_name'][] = '积分';

                //积分抵扣金额参数
                $bill_array['use_points']['argus_array'] = array(
                    'operator' => $operator,
                    'pcustID' => $bill_array['pcustID'],
                    'subjectId' => G_POINTS_ID,
                    'amount' => $bill_array['use_points']['points'],
                    'remark' => '订单 '.$bill_no.' 冻结,账户积分'
                );

            }

            //使用了优惠券抵扣金额
            if ($bill_array['master']['bill_coupon_money'] > 0) {

                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => 4,
                    'payTypeName' => '优惠券',
                    'type' => 6,
                    'pay_amount' => $bill_array['master']['bill_coupon_money'],
                    'deduct_amount' => $bill_array['master']['bill_coupon_money']
                );

                $temp_array['pay_id'][] = 4;
                $temp_array['pay_name'][] = '优惠券';

            }

            //使用了代金卡抵扣金额
            if ($bill_array['master']['bill_card_money'] > 0) {

                //生成代一条金卡支付数据
                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => 5,
                    'payTypeName' => '代金卡',
                    'type' => 7,
                    'pay_amount' => $bill_array['master']['bill_card_money'],
                    'deduct_amount' => $bill_array['master']['bill_card_money']
                );

                $temp_array['pay_id'][] = 5;
                $temp_array['pay_name'][] = '代金卡';

            }

            $surplus_money -= $paid;

            //保存订单支付信息
            if ($surplus_money >= 0 && $paid == 0) {

                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => $bill_array['master']['payTypeID'],
                    'payTypeName' => $bill_array['master']['payTypeName'],
                    'type' => $bill_array['master']['pay_type'],
                    'pay_amount' => $surplus_money,
                    'deduct_amount' => 0,
                    'payment_method_id' => $bill_array['master']['payment_method_id'],
                    'payment_method_name' => $bill_array['master']['payment_method_name'],
                    'payment_method_type' => $bill_array['master']['payment_method_type']
                );

                $temp_array['pay_id'][] = $bill_array['master']['payTypeID'];
                $temp_array['pay_name'][] = $bill_array['master']['payTypeName'];

            }

            /**
             * 异地付款
             */
            if(isset($bill_array['other_address_pay'])){

                $bill_array['bill_other_address_pay'] = array(
                    'timeStamp'=> $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'bill_code' => $bill_code,
                    'custName' => $bill_array['other_address_pay']['custName'],
                    'mobile' => $bill_array['other_address_pay']['mobile'],
                    'address' => $bill_array['other_address_pay']['address'],
                    'date' => $bill_array['other_address_pay']['date'],
                    'startTime' => $bill_array['other_address_pay']['startTime'],
                    'endTime' => $bill_array['other_address_pay']['endTime']
                );
            }


            /**
             * =========================
             * 订单支付日志处理
             * =========================
             */

            foreach($bill_array['pay'] as &$new_bill_pay) {
                $bill_log_array['other'][] = '<span class="red">新增支付：</span>';
                $bill_log_array['other'][] = '　　支付名称：' . $new_bill_pay['payTypeName'];
                $bill_log_array['other'][] = '　　支付金额：' . $new_bill_pay['pay_amount'];
                $bill_log_array['other'][] = '　　已付金额：' . $new_bill_pay['deduct_amount'];
            }

            /**
             * =========================
             * 订单支付日志处理
             * =========================
             */


            //剩余订单金额等于0时，不开发票
            if ($surplus_money == 0 && isset($bill_array['master']['invoice']) && $bill_array['master']['invoice'] == 1) {
                $bill_array['master']['invoice'] = 0;
                $bill_array['master']['invoiceID'] = null;
                $bill_array['master']['invoice_type'] = null;
                $bill_array['master']['invoice_title_type'] = null;
                $bill_array['master']['invoice_title'] = null;
                $bill_array['master']['invoice_content_id'] = null;
                $bill_array['master']['invoice_content'] = null;
            }

            //保存订单主表信息
            $bill_array['master']['uuid'] = make_uuid();
            $bill_array['master']['timeStamp'] = $datetime;
            $bill_array['master']['creator'] = $operator;
            $bill_array['master']['createTime'] = $datetime;
            $bill_array['master']['bill_no'] = $bill_no;
            $bill_array['master']['bill_code'] = $bill_code;
            $bill_array['master']['pcustID'] = $bill_array['pcustID'];
            $bill_array['master']['custID'] = $custID;
            $bill_array['master']['bill_status'] = 0;
            $bill_array['master']['pay_name_str'] = implode(',', $temp_array['pay_name']);
            $bill_array['master']['pay_id_str'] = implode(',', $temp_array['pay_id']);
            $bill_array['master']['goods_name_str'] = implode(',', $temp_array['goods']);
            $bill_array['master']['coupon_code'] = implode(',', $temp_array['coupon_code']);
            $bill_array['master']['card_code'] = implode(',', $temp_array['card_code']);
            $bill_array['master']['paying_agent_str'] = implode(',', $temp_array['paying_agent_str']);

            if(isset($bill_array['master']['bill_other_address_pay'])){
                $bill_array['master']['special_status'] = 3;
            }

            if ($surplus_money == 0) {
                $bill_array['master']['pay_status'] = 1;
            } else if ($paid > 0) {
                $bill_array['master']['pay_status'] = 2;
            } else {
                $bill_array['master']['pay_status'] = 0;
            }
            $bill_array['master']['remark'] = convertVar($bill_array['master']['remark']);
            $bill_array['master']['invoice_amount'] = 0;
            if (!isset($bill_array['master']['invoice'])) {
                $bill_array['master']['invoice'] = 0;
            } else if ($bill_array['master']['invoice'] == 1) {
                $bill_array['master']['invoice_amount'] = $surplus_money;
            }

            //内部留言
            if (isset($bill_array['remark'])) {
                $bill_array['remark'] = array(
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'remark' => $bill_array['remark']
                );
            }

            //记录订单轨迹(前台下单记录)
            if( isset($bill_array['master']['billChannel']) && in_array($bill_array['master']['billChannel'], array(1, 2))){
                $this->addBillTrace( $bill_no, $operator, '您的订单已建立');
            }

            //保存会员购买记录
            $bill_array['cust_buy_log'] = array(
                'uuid' => make_uuid(),
                'timeStamp' => $datetime,
                'creator' => $operator,
                'createTime' => $datetime,
                'pcustID' => $bill_array['pcustID'],
                'deliverID' => $bill_array['master']['deliverid'],
                'send_region_id' => $bill_array['master']['send_region_id'],
                'payTypeID' => $bill_array['master']['payTypeID'],
                'pay_type' => $bill_array['master']['pay_type'],
                'invoiceID' => isset($bill_array['master']['invoiceID']) ? $bill_array['master']['invoiceID'] : 0,
                'payment_method_id' => 0,
                'extend_1' => null,
                'extend_2' => null,
                'extend_3' => null,
                'extend_4' => null,
                'extend_5' => null,
                'extend_6' => null,
            );


            /**
             * ======================
             * 订单主信息日志
             * ======================
             */

            //订单主表信息
            $bill_log_array['other'][] = '<span class="red">订单主信息：</span>';
            $bill_log_array['other'][] = '　　城市：' . $bill_array['master']['deliver_city'];
            $bill_log_array['other'][] = '　　订单平台：' . $GLOBALS['bill_platform'][$bill_array['master']['billPlatform']];
            $bill_log_array['other'][] = '　　订单渠道：' . $GLOBALS['bill_channel'][$bill_array['master']['billChannel']];
            $bill_log_array['other'][] = '　　订单类型：' . $GLOBALS['bill_type'][$bill_array['master']['billType']]['name'];
            $bill_log_array['other'][] = '　　订单金额：' . $bill_array['master']['bill_money'];
            $bill_log_array['other'][] = '　　运费金额：' . $bill_array['master']['deliver_feePaid'];

            $distribution_name = $bill_array['master']['distribution_name'];
            if(!isset($bill_array['master']['distribution_name']) || empty($bill_array['master']['distribution_name'])){
                $distribution_name = '未分配配送站';
            }
            $bill_log_array['other'][] = '　　配送站：' . $distribution_name;
            if($bill_array['master']['pay_type'] == 1){
                $bill_log_array['other'][] = '　　付款方式：' . $bill_array['master']['payTypeName'] . '(' . $bill_array['master']['payment_method_name'] . ')';
            }elseif($bill_array['master']['pay_type'] == 2){
                $bill_log_array['other'][] = '　　付款方式：' . $bill_array['master']['payTypeName'];
            }
            $bill_log_array['other'][] = '　　赠送积分：' . $bill_array['master']['bill_totalPoints'];
            $bill_log_array['other'][] = '　　配送日期：' . $bill_array['master']['send_date'];

            if(isset($bill_array['master']['send_end_time']) && !empty($bill_array['master']['send_end_time'])){
                $send_time = $bill_array['master']['send_start_time'] . '-' . $bill_array['master']['send_end_time'];
            }else{
                $send_time = $bill_array['master']['send_start_time'];
            }
            $bill_log_array['other'][] = '　　配送时间：' . $send_time;

            //发票信息
            if($bill_array['master']['invoice'] == 1 && $bill_array['master']['invoiceID'] > 0){
                $bill_log_array['other'][] = '<span class="red">新增发票：</span>';
                $bill_log_array['other'][] = '　　发票类型：' . $GLOBALS['invoice_type'][$bill_array['master']['invoice_type']];
                $bill_log_array['other'][] = '　　抬头类型：' . $GLOBALS['invoice_title_type'][$bill_array['master']['invoice_title_type']];
                if($bill_array['master']['invoice_title_type'] == 2){
                    $bill_log_array['other'][] = '　　发票抬头：' . $bill_array['master']['invoice_title'];
                }
                $bill_log_array['other'][] = '　　发票金额：' . $bill_array['master']['invoice_amount'];
            }

            //收货地址
            if(isset($bill_array['master']['deliver_mobile']) && !empty($bill_array['master']['deliver_mobile'])){
                $log_m_p = $bill_array['master']['deliver_mobile'];
            }elseif(isset($bill_array['master']['deliver_phone']) && !empty($bill_array['master']['deliver_phone'])){
                $log_m_p = $bill_array['master']['deliver_phone'];
            }else{
                $log_m_p = '';
            }
            $deliver_address = $bill_array['master']['deliver_province'] . $bill_array['master']['deliver_city'] . $bill_array['master']['deliver_county'] . $bill_array['master']['deliver_county'];
            $bill_log_array['other'][] = '<span class="red">收货地址：</span>';
            $bill_log_array['other'][] = '　　收货人：' . $bill_array['master']['deliver_name'];
            $bill_log_array['other'][] = '　　收货人手机：' . $log_m_p;
            $bill_log_array['other'][] = '　　收货地址：' . $deliver_address;

            /**
             * ======================
             * 订单主信息日志
             * ======================
             */


            /**
             * ========================
             * 日志处理
             * ========================
             */
            $bill_array['log'] = array(
                'uuid' => make_uuid(),
                'timeStamp' => $datetime,
                //mod by allen.qiang 20141022 系统中操作信息中“操作人”切换为中文 --start
                'operator' => $operator,
//                'operator' => $G_PGLOB->currentUserName,
                //mod by allen.qiang 20141022 系统中操作信息中“操作人”切换为中文 --end
                'createTime' => $datetime,
                'logCategoryID' => 1,
                'logItem' => $bill_no,
                'extend_1' => implode('<br>', $bill_log_array['other']),
                'extend_2' => implode('<br>', $bill_log_array['goods']),
                'extend_5' => 0
            );

            $bill_array['bill_no'] = $bill_no;
            $bill_array['bill_code'] = $bill_code;

            return array( 'code' => 200, 'message' => 'ok', 'data' => array( 'bill_no' => $bill_no ,'bill_code'=> $bill_code) );

        } catch(Exception $e) {

            if ($e->getCode() > 0) {

                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );

            } else {

                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );

            }

        }

    }

    /**
     * 创建订单修改数据
     * @param $bill_array
     * @param null $operator
     * @return array
     */
    public function createAlterBillData( &$bill_array, $operator=null ) {

        //加载类文件
        quanli_include('module/base/bill/billSearch.class.php');
        quanli_include('module/base/customer/quanliCust.class.php');
        quanli_require('module/func/eai.func.php');

        //add by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
        global $G_SHOP;
        //add by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end
        //实例化ebsig接口操作类
        $ebsigEai = eai_crm();

        //订单操作记录数组
        $bill_log_array = array(
            'goods' => array(),
            'other' => array(),
            'operator' => ''
        );

        //临时数组
        $temp_array = array(
            'goods_store' => array(), //用于检查库存
            'bill_promotion' => array(), //查询订单促销
            'pay_id' => array(),
            'pay_name' => array(),
            'goods' => array(),
            'coupon_code' => array(),
            'card_code' => array(),
            'paying_agent_str' => array()
        );

        //定义判断数组
        $judge = array(
            'use_coupon_array' => array(),
            'use_points' => 0,
            'use_card_array'   => array()
        );

        $bill_array['master']['bill_money'] = 0;                                                 //订单金额
        $bill_array['master']['bill_totalMoney'] = 0;                                           //商品总金额
        $bill_array['master']['bill_totalPaid'] = 0;                                            //商品实售总金额
        $bill_array['master']['bill_receivable_money'] = 0;                                    //订单应收金额
        $bill_array['master']['bill_totalPoints'] = 0;                                          //商品总赠送积分
        $bill_array['master']['bill_subtract_money'] = 0;                                       //订单立减金额
        $bill_array['master']['bill_coupon_money'] = 0 ;                                        //订单优惠券抵扣金额
        $bill_array['master']['bill_points_money'] = 0;                                          //积分抵扣金额
        $bill_array['master']['bill_balance_money'] = 0;                                        //余额抵扣金额
        $bill_array['master']['bill_card_money'] = 0;                                            //订单代金卡抵扣金额
        $bill_array['master']['bill_totalAmount'] = 0;                                           //商品总数量
        $bill_array['master']['total_weight'] = 0;                                                //商品总重量
        $bill_array['master']['bill_accessories_money'] = 0;                                    //配件总金额
        $bill_array['master']['bill_paying_agent_money'] = 0;                                   //代付订单金额
        $bill_array['master']['tableware_amount'] = 0;                                           //餐具数量
        $bill_array['master']['candle_amount'] = 0;                                               //蜡烛数量

        $datetime = date(G_DEFAULT_DATETIME_FORMAT); //当前时间

        try {

            //实例订单查询类
            $billSearch = new billSearch();

            //实例会员类
            $quanliCust = new quanliCust();


            //查询订单信息
            $bill_master_obj = new entity('bill_master');
            $bill_master_obj->bill_no = $bill_array['bill_no'];
            if (!$this->dbca->fetch($bill_master_obj)) {
                throw new Exception('订单信息没有找到', 404);
            }
            if (in_array($bill_master_obj->bill_status, array(2, 3))) {
                throw new Exception('订单已生产，无法修改', 404);
            }
            //mod by 20141111 sunqiang FUN-BK-0021 订单为已下车状态可修改订单 start
            if (in_array($bill_master_obj->bill_status, array(4))) {
                throw new Exception('订单正在配送，无法修改', 404);
            }
//            if (in_array($bill_master_obj->bill_status, array(4, 5, 6))) {
//                throw new Exception('订单正在配送，无法修改', 404);
//            }
            //mod by 20141111 sunqiang FUN-BK-0021 订单为已下车状态可修改订单 end
            if ($bill_master_obj->bill_status == 7) {
                throw new Exception('订单已完成，无法修改', 404);
            }
            if ($bill_master_obj->bill_status == 10) {
                throw new Exception('订单已取消，无法修改', 404);
            }
            $bill_no = $bill_array['bill_no'];
            $bill_code = $bill_master_obj->bill_code;


            /**
             * 查询会员信息
             */
            $arg_array = array(
                'pcustID' => $bill_array['pcustID']
            );
            $customer_array = $quanliCust->searchCustomerDetail( $arg_array );
            if (!$customer_array) {
                throw new Exception('会员信息没有找到', 404);
            }
            $custID = $customer_array['custID'];
            if (empty($operator)) {
                $operator = $custID;
            }
            //试吃人数

            $bill_array['bill_promotion_array'] = array();

            $bill_goods_array = $bill_array['goods'];
            $bill_array['goods'] = array();

            //add by 20141222 allen.qiang FUN-AC-0029-姜饼项目-修改 start
            $product_count_jb=0; //现有商品的姜饼数量
            $product_count_yyjb=0; //获取原来的商品的姜饼数量
            //add by 20141222 allen.qiang FUN-AC-0029-姜饼项目-修改 end

            //保存订单商品信息（普通商品）
            if (isset($bill_goods_array['general'])) {

                foreach ($bill_goods_array['general'] as &$goods_array) {
                    //add by 20141222 allen.qiang FUN-AC-0029-姜饼项目-修改 start
                    if(strstr(G_ISNO_SKU,strtolower($goods_array['product_code']) )){ //判断是否是姜饼
                        $product_count_jb++;
                    }
                    //add by 20141222 allen.qiang FUN-AC-0029-姜饼项目-修改 end

                    //手动调价
                    if(isset($goods_array['adjustPrice']) && $goods_array['adjustPrice'] > -1 && $goods_array['adjustPrice'] != ''){
                        $goods_array['price'] = $goods_array['adjustPrice'];
                    }

                    //统计商品信息
                    $bill_array['master']['bill_totalMoney'] += $goods_array['salePrice'] * $goods_array['goods_amount'];    //商品总金额
                    $bill_array['master']['bill_totalPaid'] += $goods_array['price'] * $goods_array['goods_amount'];         //商品实售总金额
                    $bill_array['master']['bill_totalAmount'] += $goods_array['goods_amount'];                               //商品总数量
                    $temp_array['goods'][] = $goods_array['goodsName'];

                    if (isset($goods_array['bill_goods_no']) && !empty($goods_array['bill_goods_no'])) {
                        $bill_goods_no = $goods_array['bill_goods_no'];
                        //查询已有订单商品
                        $temp_bill_goods_array = $billSearch->searchBillGoodsDetail( $bill_no , $bill_goods_no );
                    } else {
                        $bill_goods_no = generate_seqno('seqno_bill_goods', null, true); //商品流水号
                    }

                    $goods_array['accessories_money'] = 0; //商品额外购买的配件金额

                    $goods_array['tableware_amount'] = 0;
                    $goods_array['extra_tableware_amount'] = 0;
                    $goods_array['candle_amount'] = 0;
                    $goods_array['extra_candle_amount'] = 0;

                    if ($goods_array['fittings']) {

                        foreach($goods_array['fittings'] as &$fittings) {

                            if ($fittings['forsale'] == 1 && empty($fittings['buyNum'])) {
                                continue;
                            }

                            if ($fittings['fitID'] == 51){

                                $goods_array['tableware_amount'] += $fittings['quantity'];
                                $bill_array['master']['tableware_amount'] += $fittings['quantity'];

                            } elseif ($fittings['fitID'] == 52) {

                                $goods_array['extra_tableware_amount'] += $fittings['buyNum'];
                                $bill_array['master']['tableware_amount'] += $fittings['buyNum'];

                            } elseif ($fittings['fitID'] == 53) {

                                $goods_array['candle_amount'] += $fittings['quantity'];
                                $bill_array['master']['candle_amount'] += $fittings['quantity'];

                            } elseif ($fittings['fitID'] == 55) {

                                $goods_array['extra_candle_amount'] += $fittings['buyNum'];
                                $bill_array['master']['candle_amount'] += $fittings['buyNum'];

                            }

                            $bill_array['fittings'][]= array(
                                'timeStamp' => $datetime,
                                'creator'  => $operator,
                                'createTime'  => $datetime,
                                'bill_goods_no'=> $bill_goods_no,
                                'fitID'  => $fittings['fitID'],
                                'fitName'  => $fittings['fitName'],
                                'fitUnit'  => $fittings['fitUnit'],
                                'quantity'  => $fittings['quantity'],
                                'buyNum'  => $fittings['buyNum'],
                            	//mod by yim.hu FUN-BK-0009  单价 start
                            	//'buyMoney'  => $fittings['price']
                                'buyMoney'  => $fittings['buyMoney']
                            	//mod by yim.hu FUN-BK-0009  单价 end
                            );

                            if ($fittings['forsale'] == 1) {
                                $bill_array['master']['bill_accessories_money'] += $fittings['buyMoney'] * $fittings['buyNum'];
                                $goods_array['accessories_money'] += $fittings['buyMoney'] * $fittings['buyNum'];
                            }

                        }

                    }

                    //保存订单普通商品
                    $bill_array['goods'][$bill_goods_no] = array(
                        'uuid'                     => make_uuid(),
                        'timeStamp'                => $datetime,
                        'creator'                  => $operator,
                        'createTime'               => $datetime,
                        'bill_no'                  => $bill_no,
                        'bill_goods_no'            => $bill_goods_no,
                        'goods_goodsID'           => $goods_array['goodsID'],
                        'goods_postID'            => $goods_array['postID'],
                        'goods_name'               => $goods_array['goodsName'],
                        'goods_spec'               => $goods_array['spec'],
                        'goods_amount'             => $goods_array['goods_amount'],
                        'goods_marketPrice'       => $goods_array['marketPrice'],
                        'goods_storePrice'        => $goods_array['salePrice'],
                        'goods_purchasePrice'     => $goods_array['price'],
                        'goods_points'             => $goods_array['salePoints'],
                        'goods_from'               => $goods_array['goods_from'],
                        'goods_groupID'            => 0,
                        'goods_status'             => 1,
                        'goods_weight'             => $goods_array['goodsWeight'],
                        'product_code'             => $goods_array['product_code'],
                        'birthday_card'            => $goods_array['birthday_card'],
                        'segmentation'             => $goods_array['segmentation'],
                        'goods_remark'             => $goods_array['productRemark'],     //商品生产备注
                        'tableware_amount'         => $goods_array['tableware_amount'],            //餐具数量
                        'extra_tableware_amount'   => $goods_array['extra_tableware_amount'],            //额外餐具数量（加购）
                        'candle_amount'            => $goods_array['candle_amount'],            //蜡烛数量
                        'extra_candle_amount'      => $goods_array['extra_candle_amount'],            //额外蜡烛数量（加购）
                        'auth_alter' => isset($goods_array['adjustPrice']) && $goods_array['adjustPrice'] != -1 ? 1 : 0


                    );
                    if (isset($temp_bill_goods_array)) {
                        $bill_array['goods'][$bill_goods_no]['print_num'] = $temp_bill_goods_array['print_num'];
                        $bill_array['goods'][$bill_goods_no]['print_operator'] = $temp_bill_goods_array['print_operator'];
                        $bill_array['goods'][$bill_goods_no]['print_time'] = $temp_bill_goods_array['print_time'];
                        $bill_array['goods'][$bill_goods_no]['is_voucher'] = $temp_bill_goods_array['is_voucher'];
                        $bill_array['goods'][$bill_goods_no]['voucher_operator'] = $temp_bill_goods_array['voucher_operator'];
                        $bill_array['goods'][$bill_goods_no]['voucher_time'] = $temp_bill_goods_array['voucher_time'];
                        $bill_array['goods'][$bill_goods_no]['is_warehouse'] = $temp_bill_goods_array['is_warehouse'];
                        $bill_array['goods'][$bill_goods_no]['warehouse_operator'] = $temp_bill_goods_array['warehouse_operator'];
                        $bill_array['goods'][$bill_goods_no]['warehouse_time'] = $temp_bill_goods_array['warehouse_time'];
                        $bill_array['goods'][$bill_goods_no]['is_busScan'] = $temp_bill_goods_array['is_busScan'];
                        $bill_array['goods'][$bill_goods_no]['busScan_operator'] = $temp_bill_goods_array['busScan_operator'];
                        $bill_array['goods'][$bill_goods_no]['busScan_time'] = $temp_bill_goods_array['busScan_time'];
                    }

                    /*
                     *=====================================
                     * 保存商品促销记录
                     * @author create by allen.qiang
                     * ====================================
                     */
                    if(isset($goods_array['goods_promotion']) && !empty($goods_array['goods_promotion'])){

                        foreach($goods_array['goods_promotion'] as &$p){

                            $promotionID = $p['promotionID'];
                            $promotionName = $p['remark'];
                            switch($p['type']){
                                case 1: //商品立减
                                    $promotionInfo = '立减：'.$p['money'];
                                    break;
                                case 2:  //商品特价
                                    $promotionInfo = '特价：'.$p['money'];
                                    break;
                                case 6: //商品打折
                                    $promotionInfo = '折扣：'.$p['money'];
                                    break;
                            }

                            $bill_array['bill_promotion_array'][] = array(
                                'creator' => $operator,
                                'bill_no' => $bill_no,
                                'bill_goods_no' => $bill_goods_no,
                                'promotionID' => $promotionID,
                                'promotionName' => $promotionName,
                                'promotionInfo' => $promotionInfo,
                                'promotionType' => 2
                            );
                        }
                    }

                }
            }

            if ($bill_array['master']['bill_totalAmount'] == 0 && !isset($bill_array['bill_paying_agent'])) {
                throw new Exception('订单商品为空，请选择商品', 404);
            }

            /**
             * =========================
             * 商品修改日志
             * =========================
             */

            //查询已有订单商品
            $bill_goods_array = $billSearch->searchBillGoods( array( 'bill_no' => $bill_no ) );
            //add by 20141222 allen.qiang FUN-AC-0029-姜饼项目-修改 start
            foreach($bill_goods_array as &$bill_goods) {
                if(strstr(G_ISNO_SKU,strtolower($bill_goods['product_code']) )){ //判断原来的商品是否有姜饼
                    $product_count_yyjb++;
                }
            }
            //add by 20141222 allen.qiang FUN-AC-0029-姜饼项目-修改 end
            foreach($bill_array['goods'] as &$new_bill_goods) {
                $bill_goods_no = $new_bill_goods['bill_goods_no'];
                if (isset($bill_goods_array[$bill_goods_no])) {
                    $goods_alter_array = array();
                    $old_bill_goods_array = $bill_goods_array[$bill_goods_no];
                    if ($new_bill_goods['goods_purchasePrice'] != $old_bill_goods_array['goods_purchasePrice']) {
                        $goods_alter_array[] = '　　商品价格：' . $old_bill_goods_array['goods_purchasePrice'] . ' -> ' . $new_bill_goods['goods_purchasePrice'];
                    }
                    if ($new_bill_goods['birthday_card'] != $old_bill_goods_array['birthday_card']) {
                        $goods_alter_array[] = '　　  生日牌：' . $old_bill_goods_array['birthday_card'] . ' -> ' . $new_bill_goods['birthday_card'];
                    }
                    if ($new_bill_goods['segmentation'] != $old_bill_goods_array['segmentation']) {
                        $goods_alter_array[] = '　　    切分：' . $old_bill_goods_array['segmentation'] . ' -> ' . $new_bill_goods['segmentation'];
                    }
                    if ($new_bill_goods['goods_remark'] != $old_bill_goods_array['goods_remark']) {
                        $goods_alter_array[] = '　　    备注：' . $old_bill_goods_array['goods_remark'] . ' -> ' . $new_bill_goods['goods_remark'];
                    }
                    if ($new_bill_goods['tableware_amount'] != $old_bill_goods_array['tableware_amount']) {
                        $goods_alter_array[] = '　　餐具数量：' . $old_bill_goods_array['tableware_amount'] . ' -> ' . $new_bill_goods['tableware_amount'];
                    }
                    if ($new_bill_goods['extra_tableware_amount'] != $old_bill_goods_array['extra_tableware_amount']) {
                        $goods_alter_array[] = '加购餐具数量：' . $old_bill_goods_array['extra_tableware_amount'] . ' -> ' . $new_bill_goods['extra_tableware_amount'];
                    }
                    if ($new_bill_goods['candle_amount'] != $old_bill_goods_array['candle_amount']) {
                        $goods_alter_array[] = '　　蜡烛数量：' . $old_bill_goods_array['candle_amount'] . ' -> ' . $new_bill_goods['candle_amount'];
                    }
                    if ($new_bill_goods['extra_candle_amount'] != $old_bill_goods_array['extra_candle_amount']) {
                        $goods_alter_array[] = '额外蜡烛数量：' . $old_bill_goods_array['extra_candle_amount'] . ' -> ' . $new_bill_goods['extra_candle_amount'];
                    }
                    if (count($goods_alter_array) > 1) {
                        $bill_log_array['goods'][] = '<span class="red">修改商品：</span>';
                        $bill_log_array['goods'][] = '　　商品名称：' . $new_bill_goods['goods_name'];
                        $bill_log_array['goods'][] = '　　商品规格：' . $new_bill_goods['goods_spec'];
                        foreach($goods_alter_array as &$alter) {
                            $bill_log_array['goods'][] = $alter;
                        }
                    }
                    unset($bill_goods_array[$bill_goods_no]);
                } else {
                    $bill_log_array['goods'][] = '<span class="red">新增商品：</span>';
                    $bill_log_array['goods'][] = '　　商品名称：' . $new_bill_goods['goods_name'];
                    $bill_log_array['goods'][] = '　　商品规格：' . $new_bill_goods['goods_spec'];
                    $bill_log_array['goods'][] = '　　商品价格：' . $new_bill_goods['goods_purchasePrice'];
                    $bill_log_array['goods'][] = '　　　生日牌：' . $new_bill_goods['birthday_card'];
                    $bill_log_array['goods'][] = '　　　　切分：' . $new_bill_goods['segmentation'];
                    $bill_log_array['goods'][] = '　　　　备注：' . $new_bill_goods['goods_remark'];
                    $bill_log_array['goods'][] = '　　餐具数量：' . $new_bill_goods['tableware_amount'];
                    $bill_log_array['goods'][] = '加购餐具数量：' . $new_bill_goods['extra_tableware_amount'];
                    $bill_log_array['goods'][] = '　　蜡烛数量：' . $new_bill_goods['candle_amount'];
                    $bill_log_array['goods'][] = '额外蜡烛数量：' . $new_bill_goods['extra_candle_amount'];
                    //add allen.qiang 20141110 新增商品流水号 ---start
                    $bill_log_array['goods'][] = '商品流水号：' . $new_bill_goods['bill_goods_no'];
                    //add allen.qiang 20141110 新增商品流水号 ---end
                }
            }
            if ($bill_goods_array) {
                foreach($bill_goods_array as &$bill_goods) {
                    $bill_log_array['goods'][] = '<span class="red">删除商品：</span>';
                    $bill_log_array['goods'][] = '　　商品名称：' . $bill_goods['goods_name'];
                    $bill_log_array['goods'][] = '　　商品规格：' . $bill_goods['goods_spec'];
                    $bill_log_array['goods'][] = '　　商品价格：' . $bill_goods['goods_purchasePrice'];
                    $bill_log_array['goods'][] = '　　　生日牌：' . $bill_goods['birthday_card'];
                    $bill_log_array['goods'][] = '　　　　切分：' . $bill_goods['segmentation'];
                    $bill_log_array['goods'][] = '　　　　备注：' . $bill_goods['goods_remark'];
                    $bill_log_array['goods'][] = '　　餐具数量：' . $bill_goods['tableware_amount'];
                    $bill_log_array['goods'][] = '加购餐具数量：' . $bill_goods['extra_tableware_amount'];
                    $bill_log_array['goods'][] = '　　蜡烛数量：' . $bill_goods['candle_amount'];
                    $bill_log_array['goods'][] = '额外蜡烛数量：' . $bill_goods['extra_candle_amount'];
                    //add allen.qiang 20141110 新增商品流水号 ---start
                    $bill_log_array['goods'][] = '商品流水号：' . $bill_goods['bill_goods_no'];
                    //add allen.qiang 20141110 新增商品流水号 ---end
                }
            }

            /**
             * =========================
             * 商品修改日志
             * =========================
             */

            //add by 20141222 allen.qiang FUN-AC-0029-姜饼项目-修改 start
            if(($product_count_yyjb>0 && $product_count_jb>=0)||($product_count_yyjb==0 && $product_count_jb>0)){
                if($product_count_jb==$product_count_yyjb && $bill_master_obj->bill_product_amount==0){
                    $product_count=$product_count_jb;
                }else{
                    $product_count=$bill_master_obj->bill_product_amount+($product_count_jb-$product_count_yyjb);
                }
                $bill_array['master']["bill_product_amount"]=$product_count; //订单商品生产总数量
                $bill_array['master']["bill_voucher_amount"]=$product_count_jb; //订单商品入库总数量
                $bill_array['master']["bill_out_warehouse_amount"]=$product_count_jb; //订单商品出库总数量
                $bill_array['master']["bill_busScan_amount"]=$product_count_jb; //订单商品下车总数量
            }
            //add by 20141222 allen.qiang FUN-AC-0029-姜饼项目-修改 end


            /**
             * =========================
             * 优惠券处理
             * =========================
             */

            //查询订单已使用的优惠券
            $bill_coupon_array = $billSearch->searchBillUsedCoupon( $bill_no );

            if (!empty($bill_array['use_coupon'])) {
                foreach($bill_array['use_coupon'] as $code => &$coupon) {
                    if (isset($bill_coupon_array[$code])) {
                        unset($bill_coupon_array[$code]);
                    } else {
                        $bill_log_array['other'][] = '<span class="red">新增优惠券：</span>';
                        $bill_log_array['other'][] = '　　优惠券名称：' . $coupon['couponName'];
                        $bill_log_array['other'][] = '　　优惠券金额：' . $coupon['amount'];
                        $bill_log_array['other'][] = '　　优惠券使用类型：' . $GLOBALS['coupon_use_type'][$coupon['useType']];
                    }
                    $coupon['creator'] = $operator;
                    $coupon['bill_no'] = $bill_no;
                    $bill_array['master']['bill_coupon_money'] += $coupon['amount'];
                }
            }
            if ($bill_coupon_array) {
                foreach($bill_coupon_array as &$bill_coupon) {
                    $bill_log_array['other'][] = '<span class="red">删除优惠券：</span>';
                    $bill_log_array['other'][] = '　　优惠券名称：' . $bill_coupon['couponName'];
                    $bill_log_array['other'][] = '　　优惠券金额：' . $bill_coupon['amount'];
                    $bill_log_array['other'][] = '　　优惠券使用类型：' . $bill_coupon['useType'] == 1 ? '券' : '红包';
                }
            }

            /**
             * =========================
             * 优惠券处理
             * =========================
             */


            /**
             * =========================
             * 代金卡处理
             * =========================
             */

            //查询订单已使用的优惠券
            $bill_card_array = $billSearch->searchBillUsedCard( $bill_no );

            if (isset($bill_array['use_card']) && !empty($bill_array['use_card'])) {

                foreach($bill_array['use_card']['detail'] as &$card) {

                    if (isset($bill_card_array[$card['card_no']])) {
                        unset($bill_card_array[$card['card_no']]);
                    } else {
                        $bill_log_array['other'][] = '<span class="red">新增现金卡：</span>';
                        $bill_log_array['other'][] = '　　现金卡名称：' . $card['card_name'];
                        $bill_log_array['other'][] = '　　现金卡卡号：' . $card['card_no'];
                        $bill_log_array['other'][] = '　　现金卡面值：' . $card['face_value'];
                        $bill_log_array['other'][] = '　　现金卡抵扣金额：' . $card['deducation'];
                    }

                    $card['creator'] = $operator;
                    $card['bill_no'] = $bill_no;
                    $card['bill_code'] = $bill_code;
                    $bill_array['master']['bill_card_money'] += $card['deducation'];

                }

            }
            if ($bill_card_array) {
                foreach($bill_card_array as &$bill_card) {
                    $bill_log_array['other'][] = '<span class="red">删除现金卡：</span>';
                    $bill_log_array['other'][] = '　　现金卡名称：' . $bill_card['card_name'];
                    $bill_log_array['other'][] = '　　现金卡卡号：' . $bill_card['card_no'];
                    $bill_log_array['other'][] = '　　现金卡面值：' . $bill_card['face_value'];
                    $bill_log_array['other'][] = '　　现金卡抵扣金额：' . $bill_card['deducation'];
                }
            }
            /**
             * =========================
             * 代金卡处理
             * =========================
             */


            /**
             * =========================
             * 积分处理
             * =========================
             */
            if (isset($bill_array['use_points']) && !empty($bill_array['use_points'])) {
                $bill_array['master']['bill_points_money'] += $bill_array['use_points']['bill_points_money'];
            }
            /**
             * =========================
             * 积分处理
             * =========================
             */


            /**
             * =========================
             * 余额处理
             * =========================
             */
            if (isset($bill_array['use_balance']) && !empty($bill_array['use_balance'])) {
                $bill_array['master']['bill_balance_money'] += $bill_array['use_balance']['balance'];
            }
            /**
             * =========================
             * 余额处理
             * =========================
             */


            /**
             * =========================
             * 代付订单处理
             * =========================
             */
            //查询代付订单
            $old_bill_paying_agent_array = $billSearch->searchBillPayingAgent( array( 'main_bill_no' => $_REQUEST['bill_no'] ) );

            if (isset($bill_array['bill_paying_agent']) && !empty($bill_array['bill_paying_agent'])) {

                $bill_paying_agent_array = $bill_array['bill_paying_agent'];
                $bill_array['bill_paying_agent'] = array();

                foreach($bill_paying_agent_array as $item) {

                    if (isset($old_bill_paying_agent_array[$item['bill_code']])) {

                        unset($old_bill_paying_agent_array[$item['bill_code']]);

                    } else {

                        $bill_log_array['other'][] = '新增代付订单：';
                        $bill_log_array['other'][] = '　　订单编号：' . $item['bill_code'];
                        $bill_log_array['other'][] = '　　代付金额：' . $item['bill_receivable_money'];

                    }

                    $bill_array['bill_paying_agent'][] = array(
                        'creator' => $operator,
                        'timeStamp' => $datetime,
                        'createTime' => $datetime,
                        'main_bill_no' => $bill_no,
                        'bill_no' => $item['bill_no'],
                        'bill_code' => $item['bill_code'],
                        'deliver_name' => $item['deliver_name'],
                        'bill_receivable_money' => $item['bill_receivable_money'],
                    );


                    $bill_array['master']['bill_paying_agent_money'] += $item['bill_receivable_money'];

                    $temp_array['paying_agent_str'][] = $item['bill_code'];

                }

            }


            if ($old_bill_paying_agent_array) {
                foreach($old_bill_paying_agent_array as &$bill_paying_agent) {
                    $bill_log_array['other'][] = '删除代付订单：';
                    $bill_log_array['other'][] = '　　订单编号：' . $bill_paying_agent['bill_code'];
                    $bill_log_array['other'][] = '　　代付金额：' . $bill_paying_agent['bill_receivable_money'];
                }
            }

            /**
             * =========================
             * 代付订单处理
             * =========================
             */


            //修改运费
            if( isset($bill_array['alter_freight']) && $bill_array['alter_freight']!= ''){
                $bill_array['master']['deliver_feePaid'] = $bill_array['alter_freight'];
            }

            //会员折扣促销
            if(isset($bill_array['cut_rebate_money']) && $bill_array['cut_rebate_money'] > 0){
                $bill_array['bill_promotion_array'][] = array(
                    'creator' => $operator,
                    'bill_no' => $bill_no,
                    'bill_goods_no' => 0,
                    'promotionID' => $customer_array['rankID'],           //会员等级ID
                    'promotionName' => $customer_array['rankName'],      //会员等级名称
                    'promotionInfo' => '立减：'.$bill_array['cut_rebate_money'],
                    'promotionType' => 3
                );
            }

            /**
             * ========================================
             * 查询订单促销活动
             * @author create by allen.qiang
             * =========================================
             */

            //add by sunqiang
            quanli_require('module/base/activity/activitySpike.class.php');
            $activitySpike = new activitySpike;
            if( isset($bill_array['master']['billPromotion']) && $activitySpike->billPromotion_lv5 == $bill_array['master']['billPromotion'])
            {
                $bill_array['bill_promotion'] = null;
            }
            //add by sunqiang end


            if (isset($bill_array['bill_promotion']) && !empty($bill_array['bill_promotion'])) {

                foreach($bill_array['bill_promotion'] as &$p) {

                    $promotionInfo = '';
                    switch( $p['type'] ){
                        case 1: //订单立减
                            $bill_array['master']['bill_subtract_money'] += $p['subtractMoney'];
                            $promotionInfo = '立减：'.$p['subtractMoney'];
                            break;
                        case 2: //免运费
                            $promotionInfo = '免运费：'.$bill_array['master']['deliver_feePaid'];
                            $bill_array['master']['deliver_feePaid'] = 0;
                            break;
                        case 3: //赠送优惠券
                            foreach($p['coupon'] as &$coupon) {
                                $bill_array['coupon'][] = array(
                                    'uuid' => make_uuid(),
                                    'timeStamp' => $datetime,
                                    'creator' => $operator,
                                    'createTime' => $datetime,
                                    'bill_no' => $bill_no,
                                    'couponID' => $coupon['couponID'],
                                    'couponName' => $coupon['couponName'],
                                    'couponNum' => $coupon['couponNum'],
                                    'bill_status' => $p['bill_status']
                                );
                            }
                            $promotionInfo = '赠券：'.$p['remark'];
                            break;
                        case 4: //订单打折
                            $bill_array['master']['bill_totalPaid'] = round($bill_array['master']['bill_totalPaid'] * $p['subtractMoney'], 2);
                            $bill_array['master']['bill_accessories_money'] = round($bill_array['master']['bill_accessories_money'] * $p['subtractMoney'], 2);
                            $promotionInfo = '折扣：'.$p['subtractMoney'];
                            break;
                    }
                    $bill_array['bill_promotion_array'][] = array(
                        'creator' => $operator,
                        'bill_no' => $bill_no,
                        'bill_goods_no' => 0,
                        'promotionID' => $p['promotionID'],
                        'promotionName' => $p['promotionName'],
                        'promotionInfo' => $promotionInfo,
                        'promotionType' => 1
                    );
                }
            }

            //====================================
            //订单金额 = 蛋糕 + 配件 + 运费 + 代付
            //===================================
            $bill_array['master']['bill_money'] = $bill_array['master']['bill_totalPaid']
                + $bill_array['master']['bill_accessories_money']
                + $bill_array['master']['bill_paying_agent_money'];



            //=========================================================
            //==============订单应收金额 ==============================
            //============= = 订单金额===============================
            //============= - 订单立减金额=============================
            //============= - 优惠劵抵扣金额===========================
            //============= - 代金卡抵扣金额===========================
            //============= - 积分抵扣金额）===========================
            //=========================================================
            $bill_array['master']['bill_receivable_money'] = $bill_array['master']['bill_money']
                - $bill_array['master']['bill_subtract_money']
                - $bill_array['master']['bill_coupon_money']
                - $bill_array['master']['bill_card_money']
                - $bill_array['master']['bill_points_money']
                - $bill_array['master']['bill_balance_money'];


            if ($bill_array['master']['bill_receivable_money'] < 0) {
                $bill_array['master']['bill_receivable_money'] = 0;
            }

            $bill_array['master']['bill_money'] += $bill_array['master']['deliver_feePaid'];
            $bill_array['master']['bill_receivable_money'] += $bill_array['master']['deliver_feePaid'];

            //去零取整
            if( intval($bill_array['master']['bill_receivable_money']) != $bill_array['master']['bill_receivable_money'] ){

                //抹去的小数金额
                $erase_money = $bill_array['master']['bill_receivable_money'] - intval($bill_array['master']['bill_receivable_money']);
                $bill_array['master']['bill_receivable_money'] = intval($bill_array['master']['bill_receivable_money']);

                //记录下抹去的小数金额
                $bill_array['erase_money'] = array(
                    'creator' => $operator,
                    'bill_no' => $bill_no,
                    'erase_money' => $erase_money,
                );

            }else{
                $bill_array['erase_money'] = array();
            }

            $bill_array['master']['bill_received_money'] = $bill_array['master']['bill_money'] - $bill_array['master']['bill_receivable_money'];


            //大客户试吃订单
            if (isset($bill_array['master']['foretaste']) && $bill_array['master']['foretaste'] == 1) {
                $bill_array['master']['bill_receivable_money'] = 0;
                $bill_array['master']['bill_received_money'] = 0;
                $bill_array['master']['deliver_feePaid'] = 0;
                $bill_array['master']['is_big_customer'] = 1;
            } else {
                $bill_array['master']['is_big_customer'] = 0;
            }
            //这里让4种招待赠送、生日会蛋糕、补偿订单、市场推广 和试吃一样 价格
            if($bill_array['master']['billType'] == 2 || $bill_array['master']['billType'] == 3 ||  $bill_array['master']['billType'] == 5 ||  $bill_array['master']['billType'] == 7){
            	$bill_array['master']['bill_receivable_money'] = 0;
            	$bill_array['master']['bill_received_money'] = 0;
            	$bill_array['master']['is_big_customer'] = 0;
            
            }
            //用户获取积分
            $bill_array['master']['bill_totalPoints'] = floor($bill_array['master']['bill_receivable_money']/4);

            //最终应付金额
            $surplus_money = $bill_array['master']['bill_receivable_money'];

            //已支付的金额
            $paid = 0;

            //扣除余额
            if (isset($bill_array['use_balance'])) {

                $balance = $bill_array['use_balance']['balance'];

                //查询是否已使用余额支付
                $bill_balance_pay_array = $billSearch->searchBillPay( array( 'bill_no' => $bill_no, 'payTypeID' => G_CASH_ID ) );
                if ($bill_balance_pay_array) {
                    $balance -= $bill_balance_pay_array[G_CASH_ID]['pay_amount'];
                }

                if ($balance > 0) {

                    //检查账户余额
                    $result_array = $ebsigEai->searchCustAccount($bill_array['pcustID'], G_CASH_ID);
                    if ($result_array['code'] != 200 || $result_array['data']['useableAccount'] < $balance)
                        throw new Exception('账户余额不足', 406);

                }


                //生成一条余额付款的付款记录
                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => G_CASH_ID,
                    'payTypeName' => '余额',
                    'type' => 4,
                    'pay_amount' => $bill_array['use_balance']['balance'],
                    'deduct_amount' => $bill_array['use_balance']['balance']
                );

                $temp_array['pay_id'][] = G_CASH_ID;
                $temp_array['pay_name'][] = '余额';

                //余额抵扣金额参数
                $bill_array['use_balance']['argus_array'] = array(
                    //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
                    'operator' => $operator,
//                    'operator' => $G_SHOP->currentUserName,
                    //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end
                    'pcustID' => $bill_array['pcustID'],
                    'subjectId' => G_CASH_ID,
                    'amount' => $bill_array['use_balance']['balance'],
                    'remark' => '订单 '.$bill_no.' 冻结,账户余额'
                );

            }

            //使用了积分抵扣金额
            if (isset($bill_array['use_points']) && $bill_array['use_points']['points'] > 0) {

                $points = $bill_array['use_points']['points'];

                //查询是否已使用积分支付
                $bill_balance_pay_array = $billSearch->searchBillPay( array( 'bill_no' => $bill_no, 'payTypeID' => G_POINTS_ID ) );
                if ($bill_balance_pay_array) {
                    $points -= $bill_balance_pay_array[G_POINTS_ID]['pay_amount'];
                }

                if ($points > 0) {

                    //检查账户积分
                    $result_array = $ebsigEai->searchCustAccount($bill_array['pcustID'], G_POINTS_ID);
                    if ($result_array['code'] != 200 || $result_array['data']['useableAccount'] < $points)
                        throw new Exception('账户积分不足', 406);

                }

                //生成积分支付
                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => G_POINTS_ID,
                    'payTypeName' => '积分',
                    'type' => 5,
                    'pay_amount' => $bill_array['use_points']['points'],
                    'deduct_amount' => $bill_array['use_points']['points']
                );

                $temp_array['pay_id'][] = G_POINTS_ID;
                $temp_array['pay_name'][] = '积分';

                //积分抵扣金额参数
                $bill_array['use_points']['argus_array'] = array(
                    //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
                    'operator' => $operator,
//                    'operator' => $G_SHOP->currentUserName,
                    //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end
                    'pcustID' => $bill_array['pcustID'],
                    'subjectId' => G_POINTS_ID,
                    'amount' => $bill_array['use_points']['points'],
                    'remark' => '订单 '.$bill_no.' 冻结,账户积分'
                );

            }

            //使用了优惠券抵扣金额
            if ($bill_array['master']['bill_coupon_money'] > 0) {

                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => 4,
                    'payTypeName' => '优惠券',
                    'type' => 6,
                    'pay_amount' => $bill_array['master']['bill_coupon_money'],
                    'deduct_amount' => $bill_array['master']['bill_coupon_money']
                );

                $temp_array['pay_id'][] = 4;
                $temp_array['pay_name'][] = '优惠券';

            }

            //使用了代金卡抵扣金额
            if ($bill_array['master']['bill_card_money'] > 0) {

                //生成代一条金卡支付数据
                $bill_array['pay'][] = array(
                    'uuid' => make_uuid(),
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'payTypeID' => 5,
                    'payTypeName' => '代金卡',
                    'type' => 7,
                    'pay_amount' => $bill_array['master']['bill_card_money'],
                    'deduct_amount' => $bill_array['master']['bill_card_money']
                );

                $temp_array['pay_id'][] = 5;
                $temp_array['pay_name'][] = '代金卡';

            }

            $surplus_money -= $paid;

            if ($surplus_money == 0) {
                $bill_array['master']['pay_status'] = 1;
                $bill_array['master']['invoice_amount'] = 0;
            } else if ($paid > 0) {
                $bill_array['master']['pay_status'] = 2;
                $bill_array['master']['invoice_amount'] = $surplus_money;
            } else {
                $bill_array['master']['pay_status'] = 0;
                $bill_array['master']['invoice_amount'] = $surplus_money;
            }

            if (isset($bill_array['master']['payment_method_id'])) {
                $payment_method_id = $bill_array['master']['payment_method_id'];
                $payment_method_name = $bill_array['master']['payment_method_name'];
                $payment_method_type = $bill_array['master']['payment_method_type'];
            } else {
                $payment_method_id = null;
                $payment_method_name = null;
                $payment_method_type = null;
            }

            //查询在线支付已付款
            $online_pay_array = $billSearch->searchBillPayDetail( array( 'bill_no' => $bill_no, 'type' => 2 ) );
            if ($online_pay_array && $online_pay_array['deduct_amount'] > 0) {

                //选择了其他的在线支付，系统不能存在两个在线支付
                if ($bill_array['master']['payTypeID'] != $online_pay_array['payTypeID'] && $bill_array['master']['pay_type'] == 2) {
                    throw new Exception('^_^ 出错啦！订单已存在在线支付方式', 404);
                }

                if ($online_pay_array['deduct_amount'] == $surplus_money) { //未付金额等于已在线支付金额

                    $bill_array['pay'][] = $online_pay_array;
                    $bill_array['master']['pay_status'] = 1;
                    $bill_array['master']['bill_receivable_money'] = 0;
                    $bill_array['master']['bill_received_money'] = $bill_array['master']['bill_money'];


                } else if ($online_pay_array['deduct_amount'] > $surplus_money) { //未付金额小于已在线支付金额

                    $online_pay_array['deduct_amount'] = $surplus_money;
                    $online_pay_array['pay_amount'] = $surplus_money;
                    $bill_array['pay'][] = $online_pay_array;
                    $bill_array['master']['pay_status'] = 1;
                    $bill_array['master']['bill_receivable_money'] = 0;
                    $bill_array['master']['bill_received_money'] = $bill_array['master']['bill_money'];
                    $bill_array['master']['bill_online_money'] = $online_pay_array['deduct_amount'];

                } else {

                    $bill_array['pay'][] = $online_pay_array;
                    $bill_array['master']['pay_status'] = 2;
                    $bill_array['master']['bill_receivable_money'] -= $online_pay_array['deduct_amount'];
                    $bill_array['master']['bill_received_money'] += $online_pay_array['deduct_amount'];

                    //货到付款(现金支付)支付表记录
                    $bill_array['pay'][] = array(
                        'uuid' => make_uuid(),
                        'timeStamp' => $datetime,
                        'creator' => $operator,
                        'createTime' => $datetime,
                        'bill_no' => $bill_no,
                        'payTypeID' => 1,
                        'payTypeName' => '货到付款',
                        'type' => 1,
                        'pay_amount' => $surplus_money - $online_pay_array['deduct_amount'],
                        'deduct_amount' => 0,
                        'payment_method_id' => 58,
                        'payment_method_name' => '现金支付',
                        'payment_method_type' => 1
                    );

                    $temp_array['pay_id'][] = 1;
                    $temp_array['pay_name'][] = '货到付款';

                }

                $temp_array['pay_id'][] = $bill_array['master']['payTypeID'];
                $temp_array['pay_name'][] = $bill_array['master']['payTypeName'];

            } else {

                //保存订单支付信息
                if ($surplus_money >= 0 && $paid == 0) {

                    $bill_array['pay'][] = array(
                        'uuid' => make_uuid(),
                        'timeStamp' => $datetime,
                        'creator' => $operator,
                        'createTime' => $datetime,
                        'bill_no' => $bill_no,
                        'payTypeID' => $bill_array['master']['payTypeID'],
                        'payTypeName' => $bill_array['master']['payTypeName'],
                        'type' => $bill_array['master']['pay_type'],
                        'pay_amount' => $surplus_money,
                        'deduct_amount' => 0,
                        'payment_method_id' => $payment_method_id,
                        'payment_method_name' => $payment_method_name,
                        'payment_method_type' => $payment_method_type
                    );
                    $temp_array['pay_id'][] = $bill_array['master']['payTypeID'];
                    $temp_array['pay_name'][] = $bill_array['master']['payTypeName'];

                }

            }


            /**
             * =========================
             * 订单支付日志处理
             * =========================
             */

            //查询订单支付
            $bill_pay_array = $billSearch->searchBillPay( array( 'bill_no' => $bill_no ) );

            foreach($bill_array['pay'] as &$new_bill_pay) {
                if (isset($bill_pay_array[$new_bill_pay['payTypeID']])) {

                    $old_bill_pay = $bill_pay_array[$new_bill_pay['payTypeID']];

                    $alter_pay_array = array();

                    if ($old_bill_pay['pay_amount'] != $new_bill_pay['pay_amount']) {
                        $alter_pay_array[] = '　　支付金额：' . $old_bill_pay['pay_amount'] . ' -> ' . $new_bill_pay['pay_amount'];
                    }
                    if ($old_bill_pay['deduct_amount'] != $new_bill_pay['deduct_amount']) {
                        $alter_pay_array[] = '　　已付金额：' . $old_bill_pay['deduct_amount'] . ' -> ' . $new_bill_pay['deduct_amount'];
                    }
                    if (count($alter_pay_array) > 0) {
                        $bill_log_array['other'][] = '<span class="red">修改支付：</span>';
                        $bill_log_array['other'][] = '　　支付名称：' . $new_bill_pay['payTypeName'];
                        foreach($alter_pay_array as &$alter_pay_log) {
                            $bill_log_array['other'][] = $alter_pay_log;
                        }
                    }

                    unset($bill_pay_array[$new_bill_pay['payTypeID']]);

                } else {
                    $bill_log_array['other'][] = '<span class="red">新增支付：</span>';
                    $bill_log_array['other'][] = '　　支付名称：' . $new_bill_pay['payTypeName'];
                    $bill_log_array['other'][] = '　　支付金额：' . $new_bill_pay['pay_amount'];
                    $bill_log_array['other'][] = '　　已付金额：' . $new_bill_pay['deduct_amount'];
                }
            }

            if ($bill_pay_array) {
                foreach($bill_pay_array as &$bill_pay) {
                    $bill_log_array['other'][] = '<span class="red">删除支付：</span>';
                    $bill_log_array['other'][] = '　　支付名称：' . $bill_pay['payTypeName'];
                    $bill_log_array['other'][] = '　　支付金额：' . $bill_pay['pay_amount'];
                    $bill_log_array['other'][] = '　　已付金额：' . $bill_pay['deduct_amount'];
                }
            }

            /**
             * =========================
             * 订单支付日志处理
             * =========================
             */

            //剩余订单金额等于0时，不开发票
            if ($bill_array['master']['invoice_amount'] <= 0 && isset($bill_array['master']['invoice']) && $bill_array['master']['invoice'] == 1) {
                $bill_array['master']['invoice'] = 0;
                $bill_array['master']['invoiceID'] = null;
                $bill_array['master']['invoice_type'] = null;
                $bill_array['master']['invoice_title_type'] = null;
                $bill_array['master']['invoice_title'] = null;
                $bill_array['master']['invoice_content_id'] = null;
                $bill_array['master']['invoice_content'] = null;
            }

            //保存订单主表信息
            $bill_array['master']['pay_name_str'] = implode(',', $temp_array['pay_name']);
            $bill_array['master']['pay_id_str'] = implode(',', $temp_array['pay_id']);
            $bill_array['master']['goods_name_str'] = implode(',', $temp_array['goods']);
            $bill_array['master']['coupon_code'] = implode(',', $temp_array['coupon_code']);
            $bill_array['master']['card_code'] = implode(',', $temp_array['card_code']);
            $bill_array['master']['paying_agent_str'] = implode(',', $temp_array['paying_agent_str']);
            $bill_array['master']['remark'] = convertVar($bill_array['master']['remark']);

            //内部留言
            if (isset($bill_array['remark'])) {
                $bill_array['remark'] = array(
                    'timeStamp' => $datetime,
                    'creator' => $operator,
                    'createTime' => $datetime,
                    'bill_no' => $bill_no,
                    'remark' => $bill_array['remark']
                );
            }

            //保存会员购买记录
            $bill_array['cust_buy_log'] = array(
                'uuid' => make_uuid(),
                'timeStamp' => $datetime,
                'creator' => $operator,
                'createTime' => $datetime,
                'pcustID' => $bill_array['pcustID'],
                'deliverID' => $bill_array['master']['deliverid'],
                'send_region_id' => $bill_array['master']['send_region_id'],
                'payTypeID' => $bill_array['master']['payTypeID'],
                'pay_type' => $bill_array['master']['pay_type'],
                'invoiceID' => isset($bill_array['master']['invoiceID']) ? $bill_array['master']['invoiceID'] : 0,
                'payment_method_id' => 0,
                'extend_1' => null,
                'extend_2' => null,
                'extend_3' => null,
                'extend_4' => null,
                'extend_5' => null,
                'extend_6' => null,
            );

            /**
             * ======================
             * 订单主信息日志
             * ======================
             */

            //订单主表信息
            $bill_log_array['other'][] = '<span class="red">订单主信息：</span>';
            $bill_log_array['other'][] = '　　订单金额：' . $bill_array['master']['bill_money'];
            $bill_log_array['other'][] = '　　运费金额：' . $bill_array['master']['deliver_feePaid'];

            $distribution_name = $bill_array['master']['distribution_name'];
            if(!isset($bill_array['master']['distribution_name']) || empty($bill_array['master']['distribution_name'])){
                $distribution_name = '未分配配送站';
            }
            $bill_log_array['other'][] = '　　配送站：' . $distribution_name;
            if($bill_array['master']['pay_type'] == 1){
                $bill_log_array['other'][] = '　　付款方式：' . $bill_array['master']['payTypeName'] . '(' . $bill_array['master']['payment_method_name'] . ')';
            }elseif($bill_array['master']['pay_type'] == 2){
                $bill_log_array['other'][] = '　　付款方式：' . $bill_array['master']['payTypeName'];
            }
            $bill_log_array['other'][] = '　　赠送积分：' . $bill_array['master']['bill_totalPoints'];
            $bill_log_array['other'][] = '　　配送日期：' . $bill_array['master']['send_date'];

            if(isset($bill_array['master']['send_end_time']) && !empty($bill_array['master']['send_end_time'])){
                $send_time = $bill_array['master']['send_start_time'] . '-' . $bill_array['master']['send_end_time'];
            }else{
                $send_time = $bill_array['master']['send_start_time'];
            }
            $bill_log_array['other'][] = '　　配送时间：' . $send_time;

            //发票信息
            if($bill_array['master']['invoice'] == 1 && $bill_array['master']['invoiceID'] > 0){
                $bill_log_array['other'][] = '<span class="red">新增发票：</span>';
                $bill_log_array['other'][] = '　　发票类型：' . $GLOBALS['invoice_type'][$bill_array['master']['invoice_type']];
                $bill_log_array['other'][] = '　　抬头类型：' . $GLOBALS['invoice_title_type'][$bill_array['master']['invoice_title_type']];
                if($bill_array['master']['invoice_title_type'] == 2){
                    $bill_log_array['other'][] = '　　发票抬头：' . $bill_array['master']['invoice_title'];
                }
                $bill_log_array['other'][] = '　　发票金额：' . $bill_array['master']['invoice_amount'];
            }

            //收货地址
            if(isset($bill_array['master']['deliver_mobile']) && !empty($bill_array['master']['deliver_mobile'])){
                $log_m_p = $bill_array['master']['deliver_mobile'];
            }elseif(isset($bill_array['master']['deliver_phone']) && !empty($bill_array['master']['deliver_phone'])){
                $log_m_p = $bill_array['master']['deliver_phone'];
            }else{
                $log_m_p = '';
            }
            $deliver_address = $bill_array['master']['deliver_province'] . $bill_array['master']['deliver_city'] . $bill_array['master']['deliver_county'] . $bill_array['master']['deliver_county'];
            $bill_log_array['other'][] = '<span class="red">收货地址：</span>';
            $bill_log_array['other'][] = '　　收货人：' . $bill_array['master']['deliver_name'];
            $bill_log_array['other'][] = '　　收货人手机：' . $log_m_p;
            $bill_log_array['other'][] = '　　收货地址：' . $deliver_address;

            /**
             * ======================
             * 订单主信息日志
             * ======================
             */


            /**
             * ========================
             * 日志处理
             * ========================
             */
            $bill_array['log'] = array(
                'uuid' => make_uuid(),
                'timeStamp' => $datetime,
                //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
                'operator' => $operator,
//                'operator' => $G_SHOP->currentUserName,
                //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end
                'createTime' => $datetime,
                'logCategoryID' => 1,
                'logItem' => $bill_no,
                'extend_1' => implode('<br>', $bill_log_array['other']),
                'extend_2' => implode('<br>', $bill_log_array['goods']),
                'extend_5' => $bill_array['bill_status']
            );

            $bill_array['bill_no'] = $bill_no;
            $bill_array['bill_code'] = $bill_code;

            return array( 'code' => 200, 'message' => 'ok', 'data' => array( 'bill_no' => $bill_no ,'bill_code'=> $bill_code) );

        } catch(Exception $e) {

            if ($e->getCode() > 0) {

                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );

            } else {

                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );

            }

        }

    }


    /**
     * 审核订单
     * @param array $arg_array 参数数组
     * @param bool $is_check_pay 是否检查支付状态
     * @return array
     * @throws Exception
     */
    public function auditBill( $arg_array, $is_check_pay = true ) {

        global $G_SHOP;

        //加载类文件
        quanli_include('module/base/bill/billSearch.class.php');

        //实例日志类
        $quanliLog = new quanliLog();

        //实例化订单查询类
        $billSearch = new billSearch();

        //检查参数
        if (!isset($arg_array['bill_no'], $arg_array['creator']) || empty($arg_array['bill_no'])){
            return array('code'=> 400, 'message'=> '参数错误');
        }

        $operator = !empty($_REQUEST['creator']) ? $_REQUEST['creator'] : 'system';

        try {

            $G_SHOP->DBCA->beginTransaction();

            //查询订单
            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $arg_array['bill_no'];
            if (!$G_SHOP->DBCA->fetch($bill_master)){
                throw new Exception('订单信息不存在', 404);
            }

            if (in_array($bill_master->bill_status, array(1, 2, 3, 4, 5, 6, 7))){
                throw new Exception('订单已审核，不能重复审核', 406);
            }

            if ($bill_master->bill_status == 10) {
                throw new Exception('订单已取消，审核失败', 406);
            }

            if ($is_check_pay && $bill_master->pay_type == 2 && ($bill_master->pay_status == 0 || ($bill_master->pay_status == 2 && $bill_master->bill_online_money < 0.01))){
//            if ($is_check_pay && $bill_master->pay_type == 2 && ($bill_master->pay_status == 0 || $bill_master->pay_status == 2)){
                throw new Exception('订单未付款，审核失败', 406);
            }

            $bill_master->bill_status = 1;
            $G_SHOP->DBCA->save($bill_master);

            //记录订单轨迹
            $this->addBillTrace( $arg_array['bill_no'], $operator, '您的订单已审核');

            //查询订单商品信息数组
            $arg_goods_array = array(
                'bill_no' => $bill_master->bill_no
            );
            $bill_goods_array = $billSearch->searchBillGoods( $arg_goods_array );

            if(!$bill_goods_array){
                throw new Exception('没有找到订单商品');
            }


            //非澳粒订单进行商品生产表数据保存操作
            if( $bill_master->billPlatform != 2 ){

                //add by allen.qiang 20141104 FUN-BK-0014 代付单跳流程 ---start
                $product_code_count=0; //获得订单商品编码总数量
                $product_code_dfd_count=0; //获得代付单的特殊商品编码数量
                //add by allen.qiang 20141104 FUN-BK-0014 代付单跳流程 ---end

                //add by 20141107 allen.qiang FUN-AC-0015 1元饼干订购活动 ---start
                quanli_require('module/base/activity/activityConfig.class.php');
                $activity_config = new activityConfig('yuan1');
                $config_array = $activity_config->config;
                //add by 20141107 allen.qiang FUN-AC-0015 1元饼干订购活动 ---end


                //add by 20141107 sunqiang FUN-AC-0019 9.9元饼干订购活动 ---start
                quanli_require('module/base/activity/activityConfig.class.php');
                $activity_config9 = new activityConfig('yuan9');
                $config_array9 = $activity_config9->config;
                //add by 20141107 sunqiang FUN-AC-0019 9.9元饼干订购活动 ---end

                //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 start
                $product_code_no_count=0; //订单为单一特殊商品时不用跳流程的商品数量
                //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 end

                //保存商品生产表数据
                foreach($bill_goods_array as $goods_array){

                    //add by allen.qiang 20141104 FUN-BK-0014 代付单跳流程 ---start
                    $product_code_count++;
                    if(strstr(G_TPT_SKU,strtolower($goods_array['product_code']) )){ //判断是否是代付单的特殊商品编码
                        $product_code_dfd_count++;
                    }
                    //add by allen.qiang 20141104 FUN-BK-0014 代付单跳流程 ---end

                    //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 start
                    if(strstr(G_ISNO_SKU,strtolower($goods_array['product_code']) )){ //判断是否是不用跳流程的商品编码
                        $product_code_no_count++;
                    }
                    //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 end

                    //add by 20141107 allen.qiang FUN-AC-0015 1元饼干订购活动 ---start
                    if( $bill_master->billPromotion != $config_array["billPromotion"] && $goods_array['product_code'] != $config_array["sku"] && $bill_master->billPromotion != $config_array9["billPromotion"] && $goods_array['product_code'] != $config_array9["sku"]){ //判断是否是1元饼干；1元饼干审核之后直接进入已下车，所以不需要添加bill_goods_product表数据
                    //add by 20141107 allen.qiang FUN-AC-0015 1元饼干订购活动 ---end

                        $bill_goods_product = new entity('bill_goods_product');
                        $bill_goods_product->bill_no = $goods_array['bill_no'];
                        $bill_goods_product->bill_goods_no = $goods_array['bill_goods_no'];
                        $G_SHOP->DBCA->fetch($bill_goods_product);
                        $bill_goods_product->creator = $operator;
                        $bill_goods_product->bill_code = $bill_master->bill_code;
                        $bill_goods_product->cityID = $bill_master->deliver_cityid;
                        $bill_goods_product->cityName = $bill_master->deliver_city;
                        $bill_goods_product->billType = $bill_master->billType;
                        $bill_goods_product->send_date = $bill_master->send_date;
                        $bill_goods_product->send_start_time = $bill_master->send_start_time;
                        $bill_goods_product->send_end_time = $bill_master->send_end_time;
                        $bill_goods_product->distribution_id = $bill_master->distribution_id;
                        $bill_goods_product->distribution_name = $bill_master->distribution_name;
                        $bill_goods_product->is_urgent = $bill_master->is_urgent;
                        $bill_goods_product->goods_postID = $goods_array['goods_postID'];
                        $bill_goods_product->product_code = $goods_array['product_code'];
                        $bill_goods_product->goods_name = $goods_array['goods_name'];
                        $bill_goods_product->goods_spec = $goods_array['goods_spec'];
                        $bill_goods_product->goods_amount = $goods_array['goods_amount'];
                        $bill_goods_product->tableware_amount = $goods_array['tableware_amount'];
                        $bill_goods_product->extra_tableware_amount = $goods_array['extra_tableware_amount'];
                        $bill_goods_product->candle_amount = $goods_array['candle_amount'];
                        $bill_goods_product->extra_candle_amount = $goods_array['extra_candle_amount'];
                        $bill_goods_product->birthday_card = $goods_array['birthday_card'];
                        $bill_goods_product->segmentation = $goods_array['segmentation'];
                        $bill_goods_product->goods_remark = $goods_array['goods_remark'];
                        $bill_goods_product->print_num = $goods_array['print_num'];
                        $bill_goods_product->print_operator = $goods_array['print_operator'];
                        $bill_goods_product->print_time = $goods_array['print_time'];
                        $bill_goods_product->is_voucher = $goods_array['is_voucher'];
                        $bill_goods_product->voucher_operator = $goods_array['warehouse_operator'];
                        $bill_goods_product->voucher_time = $goods_array['voucher_time'];
                        $bill_goods_product->is_warehouse = $goods_array['is_warehouse'];
                        $bill_goods_product->warehouse_operator = $goods_array['warehouse_operator'];
                        $bill_goods_product->warehouse_time = $goods_array['warehouse_time'];
                        $bill_goods_product->is_busScan = $goods_array['is_busScan'];
                        $bill_goods_product->busScan_operator = $goods_array['busScan_operator'];
                        $bill_goods_product->busScan_time = $goods_array['busScan_time'];
                        $G_SHOP->DBCA->save($bill_goods_product);

                    //add by 20141107 allen.qiang FUN-AC-0015 1元饼干订购活动 ---start
                    }
                    //add by 20141107 allen.qiang FUN-AC-0015 1元饼干订购活动 ---end
                }



                //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 start
                if($product_code_no_count!=$product_code_count){ //排除不需要跳流程的单一特殊商品
                //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 end

                    //add by allen.qiang 20141104 FUN-BK-0014 代付单跳流程 ---start
                    if(strstr(G_DISTRIBUTION_ID,$bill_master->distribution_id) && $product_code_dfd_count>0){//订单商品编码都为代付单特殊商品编码时，是上车同步下车的配送站，则设置订单表状态为已质检入库，并加入订单商品生产总数量、订单商品入库总数量
                        $bill_master->bill_product_amount=$product_code_dfd_count; //订单商品生产总数量
                        $bill_master->bill_voucher_amount=$product_code_dfd_count; //订单商品入库总数量
                        if( $product_code_count==$product_code_dfd_count){//订单中仅有ptp03、ptp04、ptp05任意sku的，订单新增提交后，即更新状态到已质检入库；
                            $bill_master->bill_status = 3;
                        }else{
                            $bill_master->bill_out_warehouse_amount=$product_code_dfd_count; //订单商品出库总数量
                            $bill_master->bill_busScan_amount=$product_code_dfd_count; //订单商品下车总数量
                        }
                        $G_SHOP->DBCA->save($bill_master);
                    } else if($product_code_dfd_count>0){ //订单商品编码都为代付单特殊商品编码时，不是上车同步下车的配送站，则设置订单表状态为已上车，并加入订单商品生产总数量、订单商品入库总数量、订单商品出库总数量
                        $bill_master->bill_product_amount=$product_code_dfd_count;//订单商品生产总数量
                        $bill_master->bill_voucher_amount=$product_code_dfd_count;//订单商品入库总数量
                        $bill_master->bill_out_warehouse_amount=$product_code_dfd_count; //订单商品出库总数量
                        if($product_code_count==$product_code_dfd_count){ //订单中仅有ptp03、ptp04、ptp05任意sku的，订单新增提交后，即更新状态到已上车；
                            $bill_master->bill_status = 4;
                        }else{
                            $bill_master->bill_busScan_amount=$product_code_dfd_count; //订单商品下车总数量
                        }
                        $G_SHOP->DBCA->save($bill_master);
                    }
                    //add by allen.qiang 20141104 FUN-BK-0014 代付单跳流程 ---end

                //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 start
                }
                //add by 20141212 allen.qiang FUN-AC-0029-姜饼项目 end

                //add by 20141106 allen.qiang FUN-AC-0015 1元饼干订购活动 ---start
                if($bill_master->billPromotion ==  $config_array["billPromotion"] || $bill_master->billPromotion ==  $config_array9["billPromotion"]){ //判断是否是1元饼干订单，是就直接把订单状态改为已下车
                    $bill_master->bill_status = 5;
                    $G_SHOP->DBCA->save($bill_master);
                }
                //add by 20141106 allen.qiang FUN-AC-0015 1元饼干订购活动 ---end

            }

            //查询订单是否为试吃订单
            $ordersql='SELECT bill_no,billType,pcustID FROM  bill_master WHERE  bill_no=?';
            $count_array = &$G_SHOP->DBCA->stmt_query($ordersql,'s',$arg_array['bill_no']);

            //试吃订单
            if($count_array[0]->billType==9){
                //修改新增客户为老客户

                $company_master = new entity('company_master');

                $company_master->pcustID = $count_array[0]->pcustID;
                $G_SHOP->DBCA->fetch($company_master);
                if($company_master && $company_master->properties==0)
                {
                    $company_master->properties = 2;
                    $G_SHOP->DBCA->save($company_master);
                }
            }

            //保存日志
            $log_array = array(
                'logCategoryID' => 1,
                'logItem' => $bill_master->bill_no,
                'extend_1' => '订单审核',
                'extend_5' => 1,
                //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
                //'operator' => $operator
                'operator' => $G_SHOP->currentUserName
                //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end

            );
            $result_array = $quanliLog->saveLogInfo( $log_array );
            if ($result_array['code'] != 200){
                throw new Exception( $result_array['message'], 400);
            }

            $G_SHOP->DBCA->commit();

            //加载短信类
            quanli_include('module/base/common/quanliSms.class.php');
            //加载订单类
            quanli_require('module/base/bill/billSearch.class.php');
            //加载会员类
            quanli_require('module/base/customer/customerManage.class.php');
            //加载配送站类
            quanli_require('module/base/system/sysDistribution.class.php');

            //实例化短信类
            $quanliSms = new quanliSms();

            //实例订单类
            $billSearch = new billSearch();

            $arg_arrays = array(
                'bill_no' => $arg_array['bill_no']
            );

            //查询订单信息
            $bill_array = $billSearch->searchBillInfo($arg_arrays);

            //查询会员信息
            $customerManage = new customerManage($G_SHOP->DBCA);

            $arg_arrays = array(
                'custID' => $bill_array[0]['custID']
            );

            $customer_array = $customerManage->getCustomerInfo($arg_arrays);
            if($bill_array){
                //生成短信内容
                $data_array = array(
                    '$bill_no' => $bill_array[0]['bill_no'],
                    '$bill_code' => $bill_array[0]['bill_code'],
                    '$operator' => $operator,
                    '$custID' => $bill_array[0]['custID'],
                    '$date_time' => date("H:i:s",time()),
                    '$date' => date("Y-m-d",time()),
                    '$send_time' => $bill_array[0]['send_date'] . " " . $bill_array[0]['send_start_time'],
                    '$send_start_time' => $bill_array[0]['send_start_time'],
                    '$send_end_time' => $bill_array[0]['send_end_time'],
                    '$distribution_technician' => $bill_array[0]['distribution_technicia']
                );
                if($customer_array){
                    $data_array['$cus_name'] = $customer_array[0]['custname'];
                    $data_array['$mobile'] = $customer_array[0]['mobile'];
                }
                if($bill_master->billType  == 8){
                    $data_array['$address'] = $bill_array[0]['deliver_all_address'];

                    $sms_content = $quanliSms->getSmsContent( 'bill_big_customer_audit', $data_array );

                    //发送短信
                    $sms_result = $quanliSms->sendSMS( $customer_array[0]['mobile'], $sms_content );

                }
                else if($bill_master->billType  == 9)
                {
                    $data_array['$address'] = $bill_array[0]['deliver_all_address'];

                    $sms_content = $quanliSms->getSmsContent( 'bill_big_customer_audit', $data_array );
                    //发送短信
                    $sms_result = $quanliSms->sendSMS(  $bill_array[0]['deliver_mobile'], $sms_content );


                }
                else if($bill_array[0]['sendTypeName'] == "自提" || $bill_array[0]['sendTypeName'] == "站点自提"){
                    //实例化配送站设置类
                    $sysDistribution = new sysDistribution( );

                    //查询配送站
                    $arg_array = array(
                        'distribution_id' => $bill_array[0]['distribution_id'],
                    );
                    $distribution_array = $sysDistribution->search( $arg_array );

                    if($distribution_array){
                        $data_array['$phone'] = $distribution_array[0]['phone'];
                        $data_array['$address'] = $distribution_array[0]['address'];
                        $data_array['$distribution_name'] = $distribution_array[0]['distribution_name'];
                    }

                    $sms_content = $quanliSms->getSmsContent( 'bill_noutoasiakas_audit', $data_array );
                    //发送短信
                    $sms_result = $quanliSms->sendSMS( $bill_array[0]['deliver_mobile'], $sms_content );

                }else{
                    $data_array['$address'] = $bill_array[0]['deliver_all_address'];
                    $sms_content = $quanliSms->getSmsContent( 'bill_audit', $data_array );
                    //发送短信
                    $sms_result = $quanliSms->sendSMS( $customer_array[0]['mobile'], $sms_content );
                }
            }
            try{
                //add by sun qiang 有订单未找到配送站
                $search_sql = "SELECT bill_code FROM bill_master
                    WHERE bill_code=?
                    AND bill_status NOT IN (10)
                    AND (distribution_id IS NULL OR distribution_id=0 OR distribution_name IS NULL)
                     ";

                $result_array_not = &$G_SHOP->DBCA->stmt_query($search_sql,"s", $bill_array[0]['bill_code']);


                if(count($result_array_not)>0)
                {
                    $code = $bill_array[0]['bill_code'];
                    //发送短信
                    $sms_result = $quanliSms->sendSMS( "13636418015", "订单[$code]异常,未匹配到配送站" );
                    $sms_result = $quanliSms->sendSMS( "13636312925", "订单[$code]异常,未匹配到配送站" );
                    $sms_result = $quanliSms->sendSMS( "18616775059", "订单[$code]异常,未匹配到配送站" );
                    $sms_result = $quanliSms->sendSMS( "18616026085", "订单[$code]异常,未匹配到配送站" );
                    $sms_result = $quanliSms->sendSMS( "15921087517", "订单[$code]异常,未匹配到配送站" );
                }
            }catch (Exception $e)
            {

            }


            return array('code'=> 200, 'message'=> '订单审核成功');

        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0){
                return array('code'=> $e->getCode(), 'message'=> $e->getMessage());
            }else {
                error_log($e->getMessage());
                return array('code'=>500, 'message'=>'系统错误');
            }

        }

    }

    /**
     * 添加订单内部留言
     * @param array $arg_array
     * @return array
     */
    public function saveBillInnerWord( $arg_array ) {

        //校验获取参数
        if (!isset($arg_array['remark'],$arg_array['bill_no']) || empty($arg_array['bill_no'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (empty($arg_array['remark'])) {
            return array( 'code' => 400, 'message' => '请输入留言' );
        }

        $creator = $_REQUEST['creator'];
        $remark = $_REQUEST['remark'];
        $bill_no = $_REQUEST['bill_no'];


        try {

            //查询订单号是否存在
            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $bill_no;
            if (!$this->dbca->fetch($bill_master)){
                throw new Exception('订单信息不存在', 404);
            }

            $bill_remark = new entity('bill_remark');
            $bill_remark->creator = $creator;
            $bill_remark->bill_no = $bill_no;
            $bill_remark->remark = $remark;
            $this->dbca->save($bill_remark);

            return array( 'code' => 200, 'message' => '添加成功', 'data' => array( 'createTime' => $bill_remark->createTime, 'remark' => $remark , 'creator' => $bill_remark->creator ) );

        } catch (Exception $e) {

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return systemError();
            }
        }

    }

    /**
     * 保存订单轨迹
     * @param int $bill_no 订单号
     * @param string $operator 操作人
     * @param string $content 轨迹内容
     * @return bool
     */
    public function addBillTrace( $bill_no, $operator, $content ) {

        global $G_SHOP;

        $bill_trace = new entity('bill_trace');
        $bill_trace->creator = $operator;
        $bill_trace->bill_no = $bill_no;
        $bill_trace->content = $content;
        $G_SHOP->DBCA->save( $bill_trace );

        return true;

    }

    /**
     * 订单取消
     * @param int $bill_no 订单号
     * @param string $operator 操作人
     * @param string $source 操作来源 backend：后台取消 shop：前端取消
     * @return array
     */
    public function cancelBill( $bill_no, $operator, $source = 'backend' ) {

        global $G_SHOP;

        //检查参数
        if (!isset($bill_no, $operator) || empty($bill_no) || empty($operator)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //加载类文件
        quanli_include('module/base/customer/logHandler.class.php');
        quanli_include('module/base/bill/billSearch.class.php');
        quanli_include('module/base/bill/billRefund.class.php');
        quanli_include('module/base/promotion/quanliCoupon.class.php');
        quanli_include('module/base/promotion/quanliCard.class.php');
        quanli_include('module/func/eai.func.php');


        //实例日志类
        $logHandler = new logHandler( $this->dbca );

        //实例订单查询类
        $billSearch = new billSearch();

        //实例优惠券类
        $ebsigCoupon = new quanliCoupon();

        //实例代金卡类
        $quanliCard = new quanliCard();

        //实例crm类
        $crm_obj = eai_crm();

        //实例退款类
        $billRefund = new billRefund( $this->dbca );

        try {

            //查询订单
            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $bill_no;
            if (!$this->dbca->fetch($bill_master)) {
                throw new Exception('订单信息不存在', 404);
            }
            if ($source == 'shop' && in_array($bill_master->bill_status, array(1, 2, 3))) {
                throw new Exception('订单已生产，不能取消', 404);
            }
            if (in_array($bill_master->bill_status, array(4, 5, 6))) {
                throw new Exception('订单已出库，不能取消', 404);
            }
            if ($bill_master->bill_status == 7) {
                throw new Exception('订单已完成，不能取消', 404);
            }
            if ($bill_master->bill_status == 10) {
                throw new Exception('订单已取消，不能重复取消', 404);
            }

            //查询代付订单
            $bill_agent = new entity('bill_paying_agent');
            $bill_agent->bill_no = $bill_no;
            if ($this->dbca->fetch($bill_agent)) {
                throw new Exception('当前订单包含代付订单，需去除代付关系后进行取消操作', 404);
            }
            
            $bill_paying_agent = new entity('bill_paying_agent');
            $bill_paying_agent->main_bill_no = $bill_no;
            if($this->dbca->fetch($bill_paying_agent)){
                throw new Exception('当前订单包含代付订单，需去除代付关系后进行取消操作', 404);
            }

            //查询订单是否为试吃订单
            $ordersql='SELECT * FROM  bill_master WHERE  bill_no=?';
            $count_array = &$G_SHOP->DBCA->stmt_query($ordersql,'s',$bill_no);
            //试吃订单 且打客户为新增客户
            if($count_array[0]->billType==9){
                $company_master = new entity('company_master');
                $company_master->pcustID = $count_array[0]->pcustID;
                $G_SHOP->DBCA->fetch($company_master);
                if($company_master && $company_master->properties==0)
                {
                    $company_master->properties = 1;
                    $G_SHOP->DBCA->save($company_master);
                }

            }



//            if($count_array[0]->billType==9 && $count_array[0]->properties==0){
//                //修改新增客户为作废客户
//                $company_master = new entity('company_master');
//                $company_master->pcustID = $count_array[0]->pcustID;
//                $G_SHOP->DBCA->fetch($company_master);
//                $company_master->properties = 1;
//                $G_SHOP->DBCA->save($company_master);
//
//            }

            //订单日志参数
            $log_array = array(
                'logCategoryID' => 1,
                'logItem' => $bill_no,
                'extend_1' => '订单取消',
                'extend_5' => 10,
                //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
                'operator' => $operator
//                'operator' => $G_SHOP->currentUserName
                //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end
            );


            /**
             * ================================
             * 检查的支付方式，现金、积分退回会员账户，在线支付已付款生成退款单
             * ================================
             */
            $pay_array = array(); //在线支付
            $cash_array = array();//现金
            $points_array = array();//积分

            $arg_array = array(
                'bill_no' => $bill_no
            );
            $bill_pay_array = $billSearch->searchBillPay( $arg_array );
            foreach ($bill_pay_array as $pay) {

                if ( $pay['type'] == 4 ) { //现金

                    $cash_array = array(
                        'pcustID' => $bill_master->pcustID,
                        'subjectId' => $pay['payTypeID'],
                        'amount' => $pay['deduct_amount'],
                        //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
                        //'operator' => $operator,
                        'operator' => $G_SHOP->currentUserName,
                        //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end
                        'remark' => '订单：'. $bill_master->bill_code . '取消，返回余额',
                    );

                } else if ($pay['type'] == 5) { //积分

                    $points_array = array(
                        'pcustID' => $bill_master->pcustID,
                        'subjectId' => $pay['payTypeID'],
                        'amount' => $pay['deduct_amount'],
                        //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
                        //'operator' => $operator,
                        'operator' => $G_SHOP->currentUserName,
                        //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end
                        'remark' => '订单：'. $bill_master->bill_code . '取消，返回积分',
                    );

                } else if ( $pay['type'] == 2 && $pay['deduct_amount'] > 0 ) { //在线支付和汇款

                    $pay_array = array(
                        'bill_no' => $bill_no,
                        'return_no' => null,
                        'custID' => $bill_master->custID,
                        'payTypeID' => $pay['payTypeID'],
                        'payTypeName' => $pay['payTypeName'],
                        'refund_amount' => $pay['deduct_amount'],
                        'refund_source' => 3,
                        //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
                        //'operator' => $operator
                        'operator' => $G_SHOP->currentUserName,
                        //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end
                    );

                }
            }
            /**
             * ================================
             * 检查的支付方式，现金、积分退回会员账户，在线支付已付款生成退款单
             * ================================
             */


            //查询订单使用的优惠券
            if ($bill_master->bill_coupon_money > 0) {
                $bill_used_coupon_array = $billSearch->searchBillUsedCoupon( $bill_no );
            }

            //查询订单使用的代金卡
            if ($bill_master->bill_card_money > 0) {
                $bill_used_card_array = $billSearch->searchBillUsedCard( $bill_no );
            }

            //订单修改对生产部、配送部的通知 保存到 bill_alter_notice
            if ($source == 'backend' && in_array($bill_master->bill_status, array( 2, 3, 4))) {

                //查询商品信息
                $arg_array = array(
                    'bill_no' => $bill_no
                );

                $bill_goods_array = $billSearch->searchBillGoods($arg_array);
                $goods_array = array();
                foreach($bill_goods_array as $goods){

                    if ($goods_array[$goods['goods_postID']]) {
                        $goods_array[$goods['goods_postID']][2] += $goods['goods_amount'];
                    } else {
                        $goods_array[$goods['goods_postID']] = array(
                            $goods['goods_name'],
                            $goods['goods_spec'],
                            $goods['goods_amount']
                        );
                    }
                }

                $goodsStr = "";

                foreach($goods_array as $data){
                    $goodsStr .= $data[0];
                    $goodsStr .= ",";
                    $goodsStr .= $data[1];
                    $goodsStr .= ",";
                    $goodsStr .= $data[2] ."个";
                    $goodsStr .= ";";
                }

                //实例化订单修改提示表
                $bill_alter_notice = new entity('bill_alter_notice');
                $bill_alter_notice->creator = $operator;
                $bill_alter_notice->createTime = $this->sys_datetime;
                $bill_alter_notice->bill_no = $bill_no;
                $bill_alter_notice->bill_code = $bill_master->bill_code;
                $bill_alter_notice->goods_info = $goodsStr;
                $bill_alter_notice->bill_status = $bill_master->bill_status;
                $bill_alter_notice->city_id = $bill_master->deliver_cityid;
                $bill_alter_notice->distribution_id = $bill_master->distribution_id;
                $bill_alter_notice->distribution_name = $bill_master->distribution_name;
                $bill_alter_notice->alter_content = '订单已取消';
                $bill_alter_notice->send_date = $bill_master->send_date;
                $bill_alter_notice->is_handle = 2;//默认未处理
                $this->dbca->save( $bill_alter_notice );

            }

        } catch (Exception $e) {

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        try {

            $this->dbca->beginTransaction();

            //取消订单
            $bill_master->bill_status = 10;
            $this->dbca->save($bill_master);

            //清除该订单在bill_goods_product的数据
            $delete_sql = 'DELETE FROM bill_goods_product WHERE bill_no = ? ';
            $G_SHOP->DBCA->stmt_query($delete_sql, 's', $bill_no);

            //记录订单轨迹
            $this->addBillTrace( $bill_no, $operator, '您的订单已取消');

            //保存订单日志
            $result_array = $logHandler->saveLogInfo( $log_array );
            if ($result_array['code'] != 200) {
                throw new Exception('链接超时，请重试', 406);
            }

            //生成退款单
            if(!empty($pay_obj)){
                $billRefund->saveBillRefund($pay_array, false);
            }


            //回滚代金卡
            if (isset($bill_used_card_array) && !empty($bill_used_card_array)) {
                foreach($bill_used_card_array as &$card) {
                    $quanliCard->rollbackCard( $card['card_no'], $bill_no );
                }
            }

            //回滚优惠券
            if (isset($bill_used_coupon_array) && !empty($bill_used_coupon_array)) {
                foreach($bill_used_coupon_array as &$coupon) {
                    if ($coupon['couponType'] == 1 || $coupon['couponType'] == 2) {
                        $ebsigCoupon->rollbackCoupon( $coupon['code'], $bill_no );
                    }
                }
            }

            //回滚现金
            if (!empty($cash_array)) {
                $result_array = $crm_obj->recharge($cash_array);
                if ($result_array['code'] != 200) {
                    throw new Exception($result_array['message'], $result_array['code']);
                }
            }

            //回滚积分
            if (!empty($points_array)) {
                $result_array = $crm_obj->recharge($points_array);
                if ($result_array['code'] != 200) {
                    throw new Exception($result_array['message'], $result_array['code']);
                }
            }

            $this->dbca->commit();

            //加载短信类
            quanli_include('module/base/common/quanliSms.class.php');
            //加载订单类
            quanli_require('module/base/bill/billSearch.class.php');
            //加载会员类
            quanli_require('module/base/customer/customerManage.class.php');

            //实例化短信类
            $quanliSms = new quanliSms();

            //实例订单类
            $billSearch = new billSearch($G_SHOP->DBCA);

            $arg_arrays = array(
                'bill_no' => $bill_no
            );

            //查询订单信息
            $bill_array = $billSearch->searchBillInfo($arg_arrays);

            //查询会员信息
            $customerManage = new customerManage($G_SHOP->DBCA);

            $arg_arrays = array(
                'custID' => $bill_array[0]['custID']
            );

            $customer_array = $customerManage->getCustomerInfo($arg_arrays);
            if($bill_array){
                //生成短信内容
                $data_array = array(
                    '$bill_no' => $bill_array[0]['bill_no'],
                    '$bill_code' => $bill_array[0]['bill_code'],
                    '$operator' => $operator,
                    '$custID' => $bill_array[0]['custID'],
                    '$date_time' => date("H:i:s",time()),
                    '$date' => date("Y-m-d",time()),
                    '$send_time' => $bill_array[0]['send_date'] . " " . $bill_array[0]['send_start_time'] . "~" . $bill_array[0]['send_end_time'],
                    '$distribution_technician' => $bill_array[0]['distribution_technicia'],

                );
                if($customer_array){
                    $data_array['$cus_name'] = $customer_array[0]['custname'];
                    $data_array['$mobile'] = $customer_array[0]['mobile'];
                }
                if($bill_master->billType  == 9){

                    $getremark_sql = 'SELECT remark FROM bill_remark WHERE bill_no=? ORDER BY createtime DESC LIMIT 1;';
                    $remarkarray = $G_SHOP->DBCA->stmt_query($getremark_sql, 's', $bill_no);
                    $data_array['$remark']="订单被驳回";
                    if($remarkarray)
                    {
                        $data_array['$remark']=$remarkarray[0]->remark;
                    }
                    $sms_content = $quanliSms->getSmsContent( 'bill_company_cancel', $data_array );
                    //发送短信
                    $quanliSms->sendSMS( $bill_array[0]['deliver_mobile'], $sms_content );
                }else{
                    $sms_content = $quanliSms->getSmsContent( 'bill_cancel', $data_array );
                    //发送短信
                    $quanliSms->sendSMS( $customer_array[0]['mobile'], $sms_content );
                }
            }
             $this->delpack($bill_no);
            return array( 'code' => 200, 'message' => '订单取消成功' );

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }


    }

    /**
     * 人工审核订单在线支付
     * @param $args_array
     * @return array
     */
    public function auditBillPay( $args_array ) {

        global $G_SHOP;

        //检查参数
        if (!isset($args_array['bill_no'], $args_array['operator'], $args_array['payTypeID']) || empty($args_array['bill_no'])
            || !quanli_is_int($args_array['payTypeID'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //实例日志类
        $quanliLog = new quanliLog();

        try {

            $this->dbca->beginTransaction();

            $bill_master = new entity('bill_master');
            $bill_master->bill_no = $args_array['bill_no'];
            if (!$this->dbca->fetch($bill_master)) {
                throw new Exception('订单信息没有找到', 404);
            }
            if ($bill_master->bill_status == 10) {
                throw new Exception('订单已取消', 404);
            }
            if ($bill_master->pay_status == 1) {
                throw new Exception('订单已付款', 406);
            }

            $bill_master->pay_status = 1;
            $bill_master->bill_online_money = $bill_master->bill_receivable_money;
            $bill_master->bill_received_money += $bill_master->bill_receivable_money;
            $bill_master->bill_receivable_money = 0;
            $this->dbca->save($bill_master);

            //检查订单支付方式并修改支付状态
            $bill_pay = new entity('bill_pay');
            $bill_pay->bill_no = $args_array['bill_no'];
            $bill_pay->payTypeID = $args_array['payTypeID'];
            if (!$this->dbca->fetch($bill_pay)) {
                throw new Exception('订单支付方式信息没有找到', 404);
            }
            if ($bill_pay->type == 1) {
                throw new Exception('该支付方式为“货到付款”，不需要支付状态确认', 404);
            }
            if ($bill_pay->deduct_amount == $bill_pay->pay_amount) {
                throw new Exception('该支付方式已付款', 404);
            }
            $bill_pay->deduct_amount = $bill_pay->pay_amount;
            $bill_pay->pay_code = isset($args_array['pay_code']) ? $args_array['pay_code'] : null;
            $bill_pay->pay_time = isset($args_array['pay_time']) ? $args_array['pay_time'] : null;
            $this->dbca->save($bill_pay);

            //更新订单轨迹
            $this->addBillTrace($args_array['bill_no'], $args_array['operator'], '您的订单付款成功');

            //保存日志
            $log_array = array(
                'logCategoryID' => 1,
                'logItem' => $bill_master->bill_no,
                'extend_1' => '支付状态确认',
                'extend_5' => $bill_master->bill_status,
                //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --start
                //'operator' => $args_array['operator']
                'operator' => $G_SHOP->currentUserName
                //mod by allen.qiang 20141023 系统中操作信息中“操作人”切换为中文 --end
            );
            $result_array = $quanliLog->saveLogInfo( $log_array );
            if ($result_array['code'] != 200)
                throw new Exception('链接超时，请重试', 404);

            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '订单支付审核成功' );

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }
 /*
 *  BD双11活动送礼包-取消订单，删除礼包
 *  @package module
 *  @backend  base
 *  @author   allen.qiang <allen.qiang@fistforward.com>
 *  20141107 add by allen.qiang FUN-AC-0013-销售BD双11活动
 */
    public function delpack( $bill_no ) {
        global $G_SHOP;

        $bill_master_sql="select bill_code from bill_master where bill_no=?";
        $bill_master_query=$G_SHOP->DBCA->stmt_query($bill_master_sql,'s',$bill_no);
        
        $del_sql="delete from activities_extend where extend_1=?";
        $del_query=$G_SHOP->DBCA->stmt_query($del_sql,'s',$bill_master_query[0]->bill_code);
 }
	//add by yim.hu 20141401 FUN-BK-0033 新增订单前CHECK --start
	//判断订单是否重复

	public function check_bill($bill_array){
		global $G_SHOP;
		//先查询bill_master表
		$master = $bill_array['master'];
		$goods = $bill_array['goods']['general'];
		$goods = array_values($goods);
		//先获取有几个蛋糕
		for($i = 0 ; $i<count($goods) ; $i++){
			/*$sql = "SELECT m.bill_code  FROM bill_master as m,bill_goods as g
			where TO_DAYS(m.createTime) = TO_DAYS(now())
			and m.pcustID = ".$bill_array['pcustID']."
			and m.payment_method_id = ".$master['payment_method_id']."
			and m.payment_method_name = '".$master['payment_method_name']."'
			and m.billType = ".$master['billType']."
			and m.billChannel = ".$master['billChannel']."
			and m.is_urgent = ".$master['urgent']."
			and m.pay_type = ".$master['pay_type']."
			and m.send_start_time = '".$master['send_start_time']."'
			and m.deliver_feePaid = '".$master['deliver_feePaid']."'
			and m.deliver_fee = '".$master['deliver_fee']."'
			and m.sendTypeID = ".$master['sendTypeID']."
			and m.deliver_mobile = '".encryptD($master['deliver_mobile'])."'
			and m.deliver_name = '".encryptD($master['deliver_name'])."'
			and m.deliver_address = '".encryptD($master['deliver_address'])."'					
			and m.deliver_county = '".$master['deliver_county']."'
			and m.deliver_city = '".$master['deliver_city']."'
			and m.deliver_province = '".$master['deliver_province']."'
			and m.deliverid = ".$master['deliverid']."
			and m.distribution_id = ".$master['distribution_id']."
			and m.invoiceID = ".$master['invoiceID']."
			and m.invoice = ".$master['invoice']."
			and m.billPromotion = ".$master['billPromotion']."
			and m.payTypeID = ".$master['payTypeID']."
			and m.send_date = '".$master['send_date']."'
			and m.billPlatform = ".$master['billPlatform']."
			and m.numPeo = ".$master['numPeo']."
			
			and g.product_code = '".$goods[$i]['product_code']."'
			and g.goods_spec = '".$goods[$i]['spec']."'
			and g.goods_status = ".$goods[$i]['goods_status']."

			and g.birthday_card = '".$goods[$i]['birthday_card']."'";
			if($goods[$i]['fittings'][1]['buyNum']!=''){
				$sql.= " and g.extra_tableware_amount = '".$goods[$i]['fittings'][1]['buyNum']."'";
					
			}
			if($goods[$i]['fittings'][3]['buyNum']!=''){
				$sql.= " and g.extra_candle_amount = '".$goods[$i]['fittings'][3]['buyNum']."'";
					
			}						
			if($goods[$i]['productRemark']!=''){
				$sql.= " and g.goods_remark = '".$goods[$i]['productRemark']."'";
					
			}
			if($master['remark']!=''){
				$sql.= " and m.remark = '".$master['remark']."'";
					
			}				

			if($master['invoice_title']!=''){
				$sql.= " and m.invoice_title = '".$master['invoice_title']."'";
					
			}
			if($master['invoice_title_type']!=''){
				$sql.= " and m.invoice_title_type = '".$master['invoice_title_type']."'";
					
			}
			if($master['send_end_time']!=''){
				$sql.= " and m.send_end_time = '".$master['send_end_time']."'";
					
			}
			if($master['deliver_phone']!=''){
				$sql.= " and m.deliver_phone = '".encryptD($master['deliver_phone'])."'";
					
			}
			if($master['deliver_postalCode']!=''){
				$sql.= " and m.deliver_postalCode = '".$master['deliver_postalCode']."'";
					
			}
			if($master['invoice_content']!=''){
				$sql.= " and m.invoice_content = '".$master['invoice_content']."'";
					
			}
				
			if($master['payTypeName']!=''){
				$sql.= " and m.payTypeName = '".$master['payTypeName']."'";
					
			}			
			$sql .=' and m.bill_no = g.bill_no';

			$master_result =  $G_SHOP->DBCA->stmt_query($sql);*/

            $master_result=$this->check_bill_search($bill_array,$master,$goods[$i] );
			if(count($master_result)>0){
				for($j=0;$j<count($master_result);$j++){
					$result[] = $master_result[$j]->bill_code;
				}				
			}else{
				return 1;
				exit();
			}

		}
		if(isset($result)){
			$result = array_count_values($result);
			foreach ($result as $key=>$v){
				if($v == count($goods)){
					$bill_code[] = '['.$key.']';			
				}			
			}			
		}else{
			return 1;
			exit();
		}		
		if(count($bill_code)>0){
		
			return "当日已有相同订单,订单号为:".implode(',',$bill_code)."请查看";
			
		}else{
			return 1;
		}
		
							
			
			

			
	}
 	//add by yim.hu 20141401 FUN-BK-0033 新增订单前CHECK --end


    /**
     * 保存/修改金额去除小数部分
     * @param $args_array array
     * @return array
     */
    public function editEraseMney( $args_array ){

        if(!isset($args_array['bill_no']) || empty($args_array['bill_no'])){
            return array( 'code' => 400, 'message' => '订单号参数错误' );
        }

        if(!isset($args_array['creator']) || empty($args_array['creator'])){
            return array( 'code' => 400, 'message' => '创建人错误' );
        }

        if(!isset($args_array['erase_money']) || !is_numeric($args_array['erase_money'])){
            return array( 'code' => 400, 'message' => '抹除小数金额参数错误' );
        }

        $bill_master = new entity('bill_master');
        $bill_master->bill_no = $args_array['bill_no'];
        if (!$this->dbca->fetch($bill_master)) {
            return array( 'code' => 400, 'message' => '订单信息没有找到' );
        }

        //实例化去除小数金额表
        $bill_erase_decimals_money = new entity('bill_erase_decimals_money');
        $bill_erase_decimals_money->bill_no = $args_array['bill_no'];
        $this->dbca->fetch($bill_erase_decimals_money);
        $bill_erase_decimals_money->creator = $args_array['creator'];
        $bill_erase_decimals_money->erase_money = $args_array['erase_money'];
        $this->dbca->save($bill_erase_decimals_money);

        return array( 'code' => 200, 'message' => '保存成功' );

    }

    /**
     * 新增订单前CHECK方法
     * add by allen.qiang 2015-01-12
     * @return array
     */
    public function check_bill_search( $bill_array,$master,$goods ){
        global $G_SHOP;

        //sql字符串
        $sql = "SELECT m.bill_code  FROM bill_master as m,bill_goods as g where TO_DAYS(m.createTime) = TO_DAYS(now()) ";

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        if (isset($bill_array['pcustID']) && !empty($bill_array['pcustID'])) {
            $sql .= ' and m.pcustID =  ?';
            $params_type .= 'i';
            $params_array[] = $bill_array['pcustID'];
        }

        if (isset($master['payment_method_id']) && !empty($master['payment_method_id'])) {
            $sql .= ' and m.payment_method_id =  ?';
            $params_type .= 'i';
            $params_array[] = $master['payment_method_id'];
        }

        if (isset($master['payment_method_name']) && !empty($master['payment_method_name'])) {
            $sql .= ' and m.payment_method_name =  ?';
            $params_type .= 's';
            $params_array[] = $master['payment_method_name'];
        }

        if (isset($master['billType']) && !empty($master['billType'])) {
            $sql .= ' and m.billType =  ?';
            $params_type .= 'i';
            $params_array[] = $master['billType'];
        }

        if (isset($master['billChannel']) && !empty($master['billChannel'])) {
            $sql .= ' and m.billChannel =  ?';
            $params_type .= 'i';
            $params_array[] = $master['billChannel'];
        }

        if (isset($master['urgent']) && !empty($master['urgent'])) {
            $sql .= ' and m.is_urgent =  ?';
            $params_type .= 'i';
            $params_array[] = $master['urgent'];
        }

        if (isset($master['pay_type']) && !empty($master['pay_type'])) {
            $sql .= ' and m.pay_type =  ?';
            $params_type .= 'i';
            $params_array[] = $master['pay_type'];
        }

        if (isset($master['send_start_time']) && !empty($master['send_start_time'])) {
            $sql .= ' and m.send_start_time =  ?';
            $params_type .= 's';
            $params_array[] = $master['send_start_time'];
        }

        if (isset($master['deliver_feePaid']) && !empty($master['deliver_feePaid'])) {
            $sql .= ' and m.deliver_feePaid =  ?';
            $params_type .= 's';
            $params_array[] = $master['deliver_feePaid'];
        }

        if (isset($master['deliver_fee']) && !empty($master['deliver_fee'])) {
            $sql .= ' and m.deliver_fee =  ?';
            $params_type .= 's';
            $params_array[] = $master['deliver_fee'];
        }

        if (isset($master['sendTypeID']) && !empty($master['sendTypeID'])) {
            $sql .= ' and m.sendTypeID =  ?';
            $params_type .= 'i';
            $params_array[] = $master['sendTypeID'];
        }

        if (isset($master['deliver_mobile']) && !empty($master['deliver_mobile'])) {
            $sql .= ' and m.deliver_mobile =  ?';
            $params_type .= 's';
            $params_array[] = encryptD($master['deliver_mobile']);
        }

        if (isset($master['deliver_name']) && !empty($master['deliver_name'])) {
            $sql .= ' and m.deliver_name =  ?';
            $params_type .= 's';
            $params_array[] = encryptD($master['deliver_name']);
        }

        if (isset($master['deliver_address']) && !empty($master['deliver_address'])) {
            $sql .= ' and m.deliver_address =  ?';
            $params_type .= 's';
            $params_array[] = encryptD($master['deliver_address']);
        }

        if (isset($master['deliver_county']) && !empty($master['deliver_county'])) {
            $sql .= ' and m.deliver_county =  ?';
            $params_type .= 's';
            $params_array[] = $master['deliver_county'];
        }

        if (isset($master['deliver_city']) && !empty($master['deliver_city'])) {
            $sql .= ' and m.deliver_city =  ?';
            $params_type .= 's';
            $params_array[] = $master['deliver_city'];
        }

        if (isset($master['deliver_province']) && !empty($master['deliver_province'])) {
            $sql .= ' and m.deliver_province =  ?';
            $params_type .= 's';
            $params_array[] = $master['deliver_province'];
        }

        if (isset($master['deliverid']) && !empty($master['deliverid'])) {
            $sql .= ' and m.deliverid =  ?';
            $params_type .= 'i';
            $params_array[] = $master['deliverid'];
        }

        if (isset($master['distribution_id']) && !empty($master['distribution_id'])) {
            $sql .= ' and m.distribution_id =  ?';
            $params_type .= 'i';
            $params_array[] = $master['distribution_id'];
        }

        if (isset($master['invoiceID']) && !empty($master['invoiceID'])) {
            $sql .= ' and m.invoiceID =  ?';
            $params_type .= 'i';
            $params_array[] = $master['invoiceID'];
        }

        if (isset($master['invoice']) && !empty($master['invoice'])) {
            $sql .= ' and m.invoice =  ?';
            $params_type .= 'i';
            $params_array[] = $master['invoice'];
        }

        if (isset($master['billPromotion']) && !empty($master['billPromotion'])) {
            $sql .= ' and m.billPromotion =  ?';
            $params_type .= 'i';
            $params_array[] = $master['billPromotion'];
        }

        if (isset($master['payTypeID']) && !empty($master['payTypeID'])) {
            $sql .= ' and m.payTypeID =  ?';
            $params_type .= 'i';
            $params_array[] = $master['payTypeID'];
        }

        if (isset($master['send_date']) && !empty($master['send_date'])) {
            $sql .= ' and m.send_date =  ?';
            $params_type .= 's';
            $params_array[] = $master['send_date'];
        }

        if (isset($master['billPlatform']) && !empty($master['billPlatform'])) {
            $sql .= ' and m.billPlatform =  ?';
            $params_type .= 'i';
            $params_array[] = $master['billPlatform'];
        }

        if (isset($master['numPeo']) && !empty($master['numPeo'])) {
            $sql .= ' and m.numPeo =  ?';
            $params_type .= 'i';
            $params_array[] = $master['numPeo'];
        }

        if (isset($goods['product_code']) && !empty($goods['product_code'])) {
            $sql .= ' and g.product_code=  ?';
            $params_type .= 's';
            $params_array[] = $goods['product_code'];
        }

        if (isset($goods['spec']) && !empty($goods['spec'])) {
            $sql .= ' and g.goods_spec =  ?';
            $params_type .= 's';
            $params_array[] = $goods['spec'];
        }

        if (isset($goods['goods_status']) && !empty($goods['goods_status'])) {
            $sql .= ' and g.goods_status =  ?';
            $params_type .= 'i';
            $params_array[] = $goods['goods_status'];
        }

        if (isset($goods['birthday_card']) && !empty($goods['birthday_card'])) {
            $sql .= ' and g.birthday_card =  ?';
            $params_type .= 's';
            $params_array[] = $goods['birthday_card'];
        }

        if(isset($goods['fittings'][1]['buyNum']) && !empty($goods['fittings'][1]['buyNum'])){
            $sql .= ' and g.extra_tableware_amount =  ?';
            $params_type .= 'i';
            $params_array[] = $goods['fittings'][1]['buyNum'];
        }

        if(isset($goods['fittings'][3]['buyNum']) && !empty($goods['fittings'][3]['buyNum'])){
            $sql .= ' and g.extra_candle_amount =  ?';
            $params_type .= 'i';
            $params_array[] = $goods['fittings'][3]['buyNum'];
        }

        if(isset($goods['productRemark']) && !empty($goods['productRemark'])){
            $sql .= ' and g.goods_remark =  ?';
            $params_type .= 's';
            $params_array[] = $goods['productRemark'];
        }

        if(isset($master['remark']) && !empty($master['remark'])){
            $sql .= ' and m.remark =  ?';
            $params_type .= 's';
            $params_array[] = $master['remark'];
        }

        if(isset($master['invoice_title']) && !empty($master['invoice_title'])){
            $sql .= ' and m.invoice_title =  ?';
            $params_type .= 's';
            $params_array[] = $master['invoice_title'];
        }

        if(isset($master['invoice_title_type']) && !empty($master['invoice_title_type'])){
            $sql .= ' and m.invoice_title_type =  ?';
            $params_type .= 'i';
            $params_array[] = $master['invoice_title_type'];
        }

        if(isset($master['send_end_time']) && !empty($master['send_end_time'])){
            $sql .= ' and m.send_end_time =  ?';
            $params_type .= 's';
            $params_array[] = $master['send_end_time'];
        }

        if(isset($master['deliver_phone']) && !empty($master['deliver_phone'])){
            $sql .= ' and m.deliver_phone =  ?';
            $params_type .= 's';
            $params_array[] = $master['deliver_phone'];
        }

        if(isset($master['deliver_postalCode']) && !empty($master['deliver_postalCode'])){
            $sql .= ' and m.deliver_postalCode =  ?';
            $params_type .= 'i';
            $params_array[] = $master['deliver_postalCode'];
        }

        if(isset($master['invoice_content']) && !empty($master['invoice_content'])){
            $sql .= ' and m.invoice_content =  ?';
            $params_type .= 's';
            $params_array[] = $master['invoice_content'];
        }

        if(isset($master['payTypeName']) && !empty($master['payTypeName'])){
            $sql .= ' and m.payTypeName =  ?';
            $params_type .= 's';
            $params_array[] = $master['payTypeName'];
        }

        $sql .=' and m.bill_no = g.bill_no';

        try{
            $temp_item_array = &$G_SHOP->DBCA->stmt_query($sql, $params_type, $params_array);
            return $temp_item_array;
        } catch (Exception $e) {
            error_log("新增订单前CHECK方法".$e->getMessage());
            return null;
        }

    }


}

